How to access current_user object in model?

后端 未结 2 1913
清歌不尽
清歌不尽 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 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!

提交回复
热议问题