简体   繁体   中英

Passing Params Hash in Rails Helper

I have a SessionsHelper , which is where I define 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 . This authenticate is in SessionsHelper , and I am running into trouble here.

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 .

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.

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

如果包括 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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