How to access current_user object in model?

后端 未结 2 1914
清歌不尽
清歌不尽 2021-01-05 21:16

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 #

d         


        
相关标签:
2条回答
  • 2021-01-05 21:47

    If you are using it only once than while calling this method pass current_user as argument like

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

    and in model

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

    If you dont want above step then follow these

    Go to User Model

    def self.current_user
      Thread.current[:user]
    end
    
    def self.current_user=(user)
      Thread.current[:user] = user
    end
    

    Then go to application controller

    before_filter :set_current_user
    
    def set_current_user
      User.current_user = current_user
    end
    

    Now we can easily fetch current_user in any model not only in Team

    just give as User.current_user so in your code

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

    So make use of it.

    Hope it solves your issue in a good way. Free to use in any model

    User.current_user to fetch the current user User.current_user= to assign the current user.

    Thanks

    0 讨论(0)
  • 2021-01-05 22:10

    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!

    0 讨论(0)
提交回复
热议问题