【发布时间】:2017-04-03 23:57:33
【问题描述】:
我正在使用一个非常标准的 has_and_belongs_to_many 关联,就像 Rails 关联指南中的示例: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
问题是我想查询以找到与零件完全匹配的组件。例如, 装配有 2 个与之关联的部件,部件的 id 为 1、2。
以下是我失败的方法:
Assembly.joins(:parts).where(parts: {id: [1,2]})
Assembly.joins(:parts).
where('parts.id IN (?)', [1,2]).
group('assemblies.id').
having('COUNT(assemblies.id) >= ?', [1,2].length)
(这个 SO 回答建议了这个:Rails scope - where in exact matches)
这些方法返回的 Assembly 对象只有 ID 为 1 和 2 的 Parts 包含在其关联的 Parts 中。但同样,我想要的只是具有这 2 个部件(ID 1 和 2)的组件。
请帮忙!
【问题讨论】:
-
@jazzinthermorning,你能说一下你用的是什么数据库吗?
-
是的,使用 PostgreSQL
标签: ruby-on-rails activerecord ruby-on-rails-5