简体   繁体   English

在Rails助手中传递参数哈希

[英]Passing Params Hash in Rails Helper

I have a SessionsHelper , which is where I define current_user : 我有一个SessionsHelper ,这是我定义current_user

module SessionsHelper
  def current_user
    @current_user ||= user_from_remember_token 
  end
  .
  .
  .
  private
  def user_from_remember_token
    User.authenticate_with_salt(*remember_token)
  end

  def remember_token
    cookies.signed[:remember_token] || [nil, nil]
  end
end

I have a UsersController that has a before_filter :authenticate . 我有一个具有before_filter :authenticateUsersController This authenticate is in SessionsHelper , and I am running into trouble here. 这个身份验证在SessionsHelper ,我在这里遇到了麻烦。

Rails handles all the cookies for me, but I built an API to use tokens for my mobile app, for which I have to send in params[:api_token] upon login and set the current_user . Rails为我处理所有的cookie,但我构建了一个API来为我的移动应用程序使用令牌,我必须在登录后发送params[:api_token]并设置current_user

I am thinking I have to do something like: 我想我必须做的事情如下:

def current_user
  @current_user ||=(user_from_remember_token || user_from_api_token)
end

but I am stuck because I am unsure if I can pass the params[:api_token] in the helper. 但我被困了,因为我不确定我是否可以在助手中传递params[:api_token]

Can anyone point me in the right direction? 谁能指出我正确的方向?

EDIT: I also have, 编辑:我也有,

class ApplicationController < ActionController::Base
  protect_from_forgery

  include SessionsHelper

  ...
end

which allows me to use before_filter :authenticate from UsersController and access this method in SessionsHelper 这允许我使用before_filter:从UsersController进行身份验证并在SessionsHelper中访问此方法

如果包括 SessionsHelperUsersController,SessionsHelper定义的方法应该有机会获得PARAMS。

If you're defining something in a helper which should be available to all views then you should put this into ApplicationHelper. 如果你在帮助器中定义了一些应该可供所有视图使用的东西,那么你应该把它放到ApplicationHelper中。

Also, I imagine you'll want to use these methods in your controllers at some point. 另外,我想你会想在某些时候在控制器中使用这些方法。 Therefore you really should define them in ApplicationController and then flag them as helper methods with the helper_method function. 因此,您确实应该在ApplicationController中定义它们,然后使用helper_method函数将它们标记为辅助方法。

Here's an example: 这是一个例子:

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :authenticate

  private

  def authenticate
    redirect_to root_url, :alert => 'You must log in to access this page' unless current_user
  end

  def current_user
    @current_user ||= User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token]
  end
  helper_method :current_user
end

There is then no need to pass params anywhere, since ApplicationController has direct access to it. 因此,无需在任何地方传递params,因为ApplicationController可以直接访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM