开发者

Setting a class variable for finding current user

开发者 https://www.devze.com 2023-01-23 14:24 出处:网络
I need to find the current logged in user in my model. I defined cattr_accessor开发者_开发百科 current_logged_in in User model.

I need to find the current logged in user in my model.

I defined cattr_accessor开发者_开发百科 current_logged_in in User model.

Now, when a user logs in I set User.current_logged_in = current_user.id.

Later, in other models I access the variable using User.current_logged_in_user. As of now it works.

Is it the right way to implement this?


A good way to implement it, unless you're just doing your code as a learning exercise is to use a plugin like devise.

That said, you should avoid accessing the current_user in models. current_user is a session thing and should not be tied to the model. Instead pass in the current_user as a parameter to methods in the model. Something like:

def can_delete_item(user)
  if user.is_admin?
    ....
  else
    .....
  end
    .....
end
0

精彩评论

暂无评论...
验证码 换一张
取 消