I wanted a variable @user to be able to accessible across all the o开发者_运维知识库ther controllers. How do i go with this.
Here is an example
Class User
def self.current=(u)
@current_user = u
end
def self.current
@current_user
end
end
You have to set User.current =
somewhere, for example in your application controller.
Then in another model or controller just call User.current
You may want to have a current_user function into your ApplicationController, something like :
def current_user
@current_user ||= User.find( session[:user_id] ) if session[:user_id].present?
end
helper_method :current_user
You may now call current_user from all your controllers and views. @Intrepidd's method is cool too.
Variables are destroyed between each call to an action.
You must re-instantiate the @user
each time.
To make it clean, you could do that in a before_filter
If you mean that you want the current user (for example), you could make a method/function in your model and call that.
精彩评论