查询关联类
如果我有一个名为 Group 的类,并且在该类中我有一个 has_many :users
我想向 Group 类添加一个方法来查看特定用户是否在该组中。如果我使用 Devise 身份验证,我可以调用 current_user。
所以我想我的第一个问题是我可以从模型中调用 current_user ,还是需要将它传递给方法?
我的第二个问题是我应该能够做类似以下的事情?
def has_access?
!current_user.nil && users.where(:id == current_user.id).count(:id) > 0
end
If I have a class called Group, and in that class I have a
has_many :users
I want to add a method to the Group class to see if a specific user is in that group. If I'm using the Devise authentication I can call the current_user.
So I guess my first question would be can I call that current_user from the model, or do I need to pass it to the method?
My second question is I should be able to do something like the following?
def has_access?
!current_user.nil && users.where(:id == current_user.id).count(:id) > 0
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在模型中调用 current_user - 它仅在控制器和视图的范围内可用。
这意味着您的方法看起来会有点不同 - 也许可以尝试以下操作:
You can't call current_user in models - it's only available within the scope of controllers and views.
Which means your method's going to look a little different - perhaps try the following:
current_user 是一个助手,因此您无法从模型访问它,并且必须将其作为参数传递给您所说的方法。
对于你的第二个问题,你能告诉我这个是在哪个类中定义的吗?
据我了解,它似乎在组模型定义中,因为您正在使用“用户”,我猜这是 has_many 关联。
如果是这样,答案显然是否定的,因为这里不知道“current_user”。
current_user is a helper so you cannot access it from a model and have to pass it as argument to the method as you said.
For your second question, Can you tell me in which class is this defined ?
As I understand, it seems to be in the Group model definition as you are using "users" which I guess is the has_many association.
If so, the answer is obviously no since "current_user" is unknowed here.