繁体   English   中英

has_and_belongs_to_many权限过滤

[英]has_and_belongs_to_many permission filtering

我需要找到两个模型之间的记录。

class Report
  has_and_belongs_to_many :groups
end

class Group
  has_and_belongs_to_many :reports
end

和join_table-report_groups

我有一个可以访问的组ID数组,例如[1, 2] 而且我需要找到具有我只能访问的组的报告。

If report has groups list like: [1], [2], [1,2] it is OK.
If report has - [1,2,3] - skip it.
If - [3,4] - skip it to.

我只需要报告允许的我的团体。

仔细检查您的联接表的名称。

Report.where(
  'NOT EXISTS(SELECT * FROM reports_groups WHERE report_id = reports.id AND group_id IN (?))',
  [1, 2],
)

为什么不将复杂查询与arel_table构建一起使用

accessible_group_ids = [1, 2, ..., n] Report.joins(:groups).where(Group.arel_table[:id].in(accessible_group_ids)).distinct

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM