2011-04-15 47 views
0

我有一些控制器和每个控制器的方法,每个方法从会话值我有下面的代码:获得每个控制器

@user = session[:user] 

有没有办法避免将代码放到每一个每一个方法控制器?

回答

2

可以在ApplicationController添加代码:

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    before_filter :current_user 

    def current_user 
    @user = session[:user] 
    end 
end 
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