Rails/Active Record has_many 通过关联 - 获取一条记录
我通过模型权限有模型角色和访问权限的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不知道对此的查询,但您可以通过 ruby 执行此操作来获取角色
作为对下面您的评论的回应,该评论会触发太多查询,请使用此方法,该方法只会触发 2 个查询。
您也可以使用此方法您的验证,
您建议 Role.includes(:accesses) 触发三个查询,而 Role.includes(:permissions) 仅触发两个
Don't know the query to this one but you can get the role through ruby doing this
As a response to your comment below that this fires too many queries, use this method which will only fire 2 queries..
You can also use this for your validation,
You suggested Role.includes(:accesses) fires three queries whereas Role.includes(:permissions) only fires two