Jayaram
Jayaram

Reputation: 839

pass a variable across multiple controllers in rails

I wanted a variable @user to be able to accessible across all the other controllers. How do i go with this.

Upvotes: 1

Views: 3359

Answers (4)

Intrepidd
Intrepidd

Reputation: 20878

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

Upvotes: 1

christianblais
christianblais

Reputation: 2458

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.

Upvotes: 1

irl_irl
irl_irl

Reputation: 3975

If you mean that you want the current user (for example), you could make a method/function in your model and call that.

Upvotes: 0

apneadiving
apneadiving

Reputation: 115521

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

Upvotes: 0

Related Questions