Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access current_user object in model?

I am trying to write a method in my "team" model but current_user is showing this error

undefined local variable or method `current_user' for #

def set_default_url
  if current_user.id == self.user_id
    "/assets/default_black_:style_logo.jpg"
  else
    "/assets/default_:style_logo.jpg"
  end
end

The method current_user is working fine for other models and controllers . I am calling this method like this .

has_attached_file :logo, :styles => { 
  :medium => "200x200#", 
  :thumb => "100x100#", 
  :small => "50x50#" 
}, 
:default_url => :set_default_url

I am using rails 3.2 , ruby 1.9.3 and devise 3.1 . It seems to be simple task but I don't understand where the fault lies . I will be really thankful if someone helps me out here .

like image 778
techdreams Avatar asked Mar 02 '15 07:03

techdreams


1 Answers

current_user is not available in any model, to access current_user in model do this

In your application controller

before_filter :set_current_user

def set_current_user
  Team.current_user = current_user
end

in your Team model add this line

cattr_accessor :current_user

Congrats, now current_user is available in every model, to get the current user just use the following line everywhere

Team.current_user

NOTE: Restart the server after adding the lines mentioned above!

Now in your question you can use it like

def set_default_url
  if Team.current_user.id == self.user_id
    "/assets/default_black_:style_logo.jpg"
  else
    "/assets/default_:style_logo.jpg"
  end
end

Hope this helps!

like image 163
Rajdeep Singh Avatar answered Oct 23 '22 10:10

Rajdeep Singh