Home > Blockchain >  ActiveRecord WHERE IN with a separate query—combine to a single INNER JOIN query
ActiveRecord WHERE IN with a separate query—combine to a single INNER JOIN query

Time:04-20

I currently have a very complicated query which (simplified) looks like:

User.where(party_id: [Party.cool_parties.pluck(:id)])

It works great, but hits the db with 2 separate queries. I'm just wondering how to combine it into a single query? Some kind of inner join with a temporary table somehow? I'm not sure how to do that with Rails...

CodePudding user response:

User.where(party_id: Party.cool_parties)

Just pass the assocation/relation and ActiveRecord will construct a subquery.

pluck should only be used in the cases where you actually want to force a query to load the data as an array - which is a lot less often then then you think.

  • Related