Rails/Active Record has_many 通过关联 - 获取一条记录

发布于 2024-12-16 02:49:51 字数 580 浏览 2 评论 0原文

我通过模型权限有模型角色和访问权限的 has_many 关系。

我遇到的情况是,任何两个角色都不应该具有相同的访问权限。因此,我创建了一个自定义验证,当当前角色(正在创建)被分配与以前存在的角色相同的访问权限时,这基本上会导致错误消息,

errors.add(:Role, "already exists with selected permissions") if Role.all.map(&:access_ids).include?(self.access_ids)

这一切都正常。现在我需要获取与当前角色具有相同访问权限的角色。那么,我该怎么做呢?我尝试过,

Role.includes(:accesses).where(:accesses => {:id => [1,2]}).count

但这会返回访问 ID 为 1 或 2 的所有角色(例如 [1, 2, 3, 4], [1], [2]) 。我需要的是获取访问 ID 恰好为 1 和 2 的角色。

如果我可以替换 '=>' 那就太好了在上面的查询中使用 '==' :) 但这显然不起作用。

I have a has_many relationship of models Role and Access through model Permission.

I have a situation that no two roles should have identical accesses. So, I created a custom validation which basically results in an error message when current role(being created) is assigned the same accesses as previously existing roles using,

errors.add(:Role, "already exists with selected permissions") if Role.all.map(&:access_ids).include?(self.access_ids)

This all works fine. Now I need to fetch the role which has identical accesses as current role. So, how do I do that ? I tried with

Role.includes(:accesses).where(:accesses => {:id => [1,2]}).count

but this returns all roles whose access ids have either 1 or 2 (say [1, 2, 3, 4], [1], [2]) . What I need is to get the role whose access ids are exactly 1 and 2.

It would be nice if i could replace '=>' with '==' in above query :) But that obviously does not work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

最好是你 2024-12-23 02:49:51

不知道对此的查询,但您可以通过 ruby​​ 执行此操作来获取角色

Role.all.to_a.find{|r| r.access_ids == self.access_ids}

作为对下面您的评论的回应,该评论会触发太多查询,请使用此方法,该方法只会触发 2 个查询。

 Role.includes(:permissions).find{|r| r.permissions.map(&:access_id) == self.access_ids}

您也可以使用此方法您的验证,

Role.includes(:permissions).any?{|r| r.permissions.map(&:access_id) == self.access_ids}

您建议 Role.includes(:accesses) 触发三个查询,而 Role.includes(:permissions) 仅触发两个

Don't know the query to this one but you can get the role through ruby doing this

Role.all.to_a.find{|r| r.access_ids == self.access_ids}

As a response to your comment below that this fires too many queries, use this method which will only fire 2 queries..

 Role.includes(:permissions).find{|r| r.permissions.map(&:access_id) == self.access_ids}

You can also use this for your validation,

Role.includes(:permissions).any?{|r| r.permissions.map(&:access_id) == self.access_ids}

You suggested Role.includes(:accesses) fires three queries whereas Role.includes(:permissions) only fires two

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