How to get the current user id in model like post.
def read?
if self.users.ids.include? @current_user
'read'
else
'unread'
end
end
If i am trying to use as @current user it not takes. Even passing through controller?
答案 0 :(得分:1)
将用户传递到可以获取价值的任何地方
def read?(user)
if self.users.ids.include? user.id
'read'
else
'unread'
end
end
答案 1 :(得分:0)
Helpers方法不能在模型内部直接访问,要访问它,您需要像这样显式调用它-
current_user = ApplicationController.helpers.current_user
但是我建议您在这种方法中将current_user
作为参数传递-
class MyModel < ApplicationRecord
#current_user = ApplicationController.helpers.current_user
def read?(user)
return self.users.ids.include?(user) ? true : false
end
end
这样将是使用此方法的便捷方法
obj = MyModel.first
obj.read?(current_user)
答案 2 :(得分:0)
除非您从控制器传递current_user
,否则无法在模型中获得它。