简体   繁体   English

查询 has_many 关系,包含 this 和 this

[英]Query has_many relationship, contains this and also this

# engine.rb
has_many :pistons

#piston.rb
belongs_to :engine

Piston has a column, piston_count and, of course, engine_id活塞有一个列,活塞piston_count ,当然还有engine_id

My database has the following 7 records我的数据库有以下 7 条记录

Engine.all
#=> [#<Engine id: 1>, #<Engine id: 2>, #<Engine id: 3>]

Piston.all
#=> [#<Piston id: 1, engine_id: 1, piston_count: 1>, #<Piston id: 2, engine_id: 1, piston_count: 2>, #<Piston id: 2, engine_id: 2, piston_count: 1>, #<Piston id: 2, engine_id: 3, piston_count: 2>]

I want to write a query that says, return the Engine containing Pistons with a piston_count of 1 and also contains a piston_count of 2我想写一个查询,返回包含活塞的Engine ,活塞piston_count1并且活塞piston_count2

I've tried... engines = Engine.joins(:pistons).merge(Piston.where(piston_count: 1)) #=> [#, #] engines.joins(:pistons).merge(Piston.where(piston_count:2)) #=> []我试过... engine = Engine.joins(:pistons).merge(Piston.where(piston_count: 1)) #=> [#, #]engine.joins(:pistons).merge(Piston.where(活塞计数:2)) #=> []

It returns an empty array because active record turns that into one AND clause.它返回一个空数组,因为活动记录将其转换为一个 AND 子句。 However, if I do an OR statement, it will return too many records.但是,如果我执行 OR 语句,它将返回太多记录。 Any thoughts?有什么想法吗?

Figured it out.弄清楚了。 This takes the intersect of both Active Record Queries.这需要两个 Active Record 查询的交集。

engine_ids = Engine.joins(:pistons).merge(Piston.where(piston_count: 1)).pluck(:id) & Engine.joins(:pistons).merge(Piston.where(piston_count: 2)).pluck(:id)

Then go back and retrieve all the intersects.然后返回并检索所有相交。

Engine.where(id: engine_ids)

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

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