简体   繁体   中英

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] ?

请尝试以下操作:

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')

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