[英]Ruby on Rails 4 - Form helper not passing a params hash to controller
[英]Passing Params Hash in Rails Helper
我有一个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
我有一个具有before_filter :authenticate
的UsersController
。 这个身份验证在SessionsHelper
,我在这里遇到了麻烦。
Rails为我处理所有的cookie,但我构建了一个API来为我的移动应用程序使用令牌,我必须在登录后发送params[:api_token]
并设置current_user
。
我想我必须做的事情如下:
def current_user
@current_user ||=(user_from_remember_token || user_from_api_token)
end
但我被困了,因为我不确定我是否可以在助手中传递params[:api_token]
。
谁能指出我正确的方向?
编辑:我也有,
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
...
end
这允许我使用before_filter:从UsersController进行身份验证并在SessionsHelper中访问此方法
如果包括 SessionsHelper在UsersController,在SessionsHelper定义的方法应该有机会获得PARAMS。
如果你在帮助器中定义了一些应该可供所有视图使用的东西,那么你应该把它放到ApplicationHelper中。
另外,我想你会想在某些时候在控制器中使用这些方法。 因此,您确实应该在ApplicationController中定义它们,然后使用helper_method函数将它们标记为辅助方法。
这是一个例子:
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
因此,无需在任何地方传递params,因为ApplicationController可以直接访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.