开发者

pass a variable across multiple controllers in rails

开发者 https://www.devze.com 2023-02-11 23:18 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号