[英]Models with has_many through to each other — how to find Model where it has a specific other Model?
Tables: 表:
Sales, Types, SaleTypes. 销售,类型,销售类型。
Sales has_many SaleTypes, has_many Types through SalesTypes. 销售has_many SaleTypes,通过SalesTypes具有has_many类型。 Types has_many SaleTypes, has_many Sales through SalesTypes. 类型has_many SaleTypes,has_many SalesTypes中的Sales。
I want to find all Sales where Types.id == 1 OR is in [1, 2, 3]. 我想找到Types.id == 1 OR在[1,2,3]中的所有Sales。
So far the best solution is to do: 到目前为止,最好的解决方案是:
Sale.joins(:sale_types).where('sale_types.type_id = ?', '1')
However, this seems unwieldy and it does not accept arrays/multiple matches. 但是,这似乎很麻烦,并且不接受数组/多个匹配项。 Is there a better way to do this? 有一个更好的方法吗?
Doing join is the best way i can think of. 加入是我能想到的最好方法。 Do this if you want to select sales based on multiple types 如果要基于多种类型选择销售,请执行此操作
Sale.joins(:sale_types).where('sale_types.type_id in (?)', types)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.