从会话中获取每个控制器的每个方法的值

时间:2011-04-15 05:57:35

标签: ruby-on-rails

我有一些控制器,在每个控制器的每个方法中我都有下一个代码:

@user = session[:user]

有没有办法避免将此代码放在每个控制器的每个方法上?

2 个答案:

答案 0 :(得分:2)

您可以在ApplicationController中添加代码:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :current_user

  def current_user
    @user = session[:user]
  end
end

答案 1 :(得分:0)

@nash的答案很好,这里提供了一个可以在每个方法/视图中使用的辅助方法。这就是像Devise这样的宝石:

class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user
  helper_method :user_signed_in?

  private  
    def current_user  
      @current_user ||= User.find_by_id(session[:user_id]) if session[:user_id]  
    end

    def user_signed_in?
      return 1 if current_user 
    end

    def authenticate_user!
      if !current_user
        flash[:error] = 'You need to sign in before accessing this page!'
        redirect_to signin_services_path
      end
    end  
end