Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and use a global variable like current_user (devise) in Rails?

In my project I need to use a global variable like the one of devise (current_user) because in the ability.rb I want to know in which project he is located. Something like current_project. Maybe an attribute of the session, like the project_id. Someone have done something like that? Thanks a lot!

like image 854
ivo Avatar asked Mar 18 '23 17:03

ivo


1 Answers

try this : You actually need to store the variable in a session. Taking the example of current_user it self :- In your application controller ( /app/controllers/application_controller.rb ) add a helper method as follows:

 class ApplicationController < ActionController::Base

  protect_from_forgery

  helper_method :current_user

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

The current_user method gets the current user by its id, using the id from the session variable, and caches the result in an instance variable. We’ll make it a helper method too so that we can use it in the application’s view code.

reference - http://railscasts.com/episodes/250-authentication-from-scratch?view=asciicast

like image 108
Shazad Maved Avatar answered Mar 20 '23 07:03

Shazad Maved