简体   繁体   中英

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

My database has the following 7 records

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

I've tried... engines = Engine.joins(:pistons).merge(Piston.where(piston_count: 1)) #=> [#, #] engines.joins(:pistons).merge(Piston.where(piston_count:2)) #=> []

It returns an empty array because active record turns that into one AND clause. However, if I do an OR statement, it will return too many records. Any thoughts?

Figured it out. This takes the intersect of both Active Record Queries.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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