notblakeshelton
notblakeshelton

Reputation: 364

find records in model based on conditions of associated model

I need a way to find all the records in a model depending on conditions of one of its associated models.
Something like this:

Product.where(:product_number => [1,3,5], customer.city => "New New York")

which would return all products whose customer's city is New New York and has a product number of either 1, 3, or 5.

My product table has a customer_id column, so I could probably just find all customers whose city is New New York, grab their id's, and then use :customer_id => customerIdArray, but is there a simpler way, like in my example? Perhaps using something like customer.city or customer[:city]?

Upvotes: 0

Views: 28

Answers (1)

vee
vee

Reputation: 38645

Try the following:

Product.joins(:customer).where('products.product_number in (:product_list) and customers.city = :customer_city', product_list: [1, 3, 5], customer_city: 'New New York')

Upvotes: 1

Related Questions