查询关联类

发布于 2024-11-09 02:37:56 字数 353 浏览 0 评论 0原文

如果我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ˉ厌 2024-11-16 02:37:56

您不能在模型中调用 current_user - 它仅在控制器和视图的范围内可用。

这意味着您的方法看起来会有点不同 - 也许可以尝试以下操作:

def has_access?(user)
  user.present? && users.where(:id => user.id).any?
end

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:

def has_access?(user)
  user.present? && users.where(:id => user.id).any?
end
风透绣罗衣 2024-11-16 02:37:56

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文