简体   繁体   English

根据关联模型的条件在模型中查找记录

[英]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. 它将返回客户所在城市为纽约且产品编号为1、3或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? 我的产品表中有一个customer_id列,因此我很可能可以找到所有城市为纽约的客户,获取其ID,然后使用:customer_id => customerIdArray ,但是有没有更简单的方法,例如在我的示例中? Perhaps using something like customer.city or customer[:city] ? 也许使用诸如customer.citycustomer[: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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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