ruby on rails - Find all records that don't have any of an associated model -


i'm using rails 3.2.

i have product model, , variant model. product can have many variants. variant can belong many products.

i want make lookup on products model, find products have specific variant count, such (pseudocode):

product.where("product.variants.count == 0")

how do activerecord?

you can use left outer join return records need. rails issues left outer join when use includes.

for example:

product.includes(:variants).where('variants.id' => nil) 

that return products there no variants. can use explicit joins.

product.joins('left outer join variants on variants.product_id = products.id').where('variants.id' => nil) 

the left outer join return records on left side of join, if right side not present. place null values associated columns, can use check negative presence, did above. can read more left joins here: http://www.w3schools.com/sql/sql_join_left.asp.

the thing solution you're not doing subqueries conditional, more performant.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -