简体   繁体   English

具有has_many的模型到彼此-如何在具有特定其他模型的地方查找模型?

[英]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.

相关问题 使用另外两个模型通过关联更新has_many中的连接模型 - Update join model in has_many through association, using the two other models 在Rails has_many通过关系中,中介模型可以服务于两个以上其他模型吗? - In a Rails has_many through relationship, can the intermediary model serve more than two other models? 同一个模型has_many属于其他模型 - Same model has_many and belongs_to to other model has_many其他模型不止一次的模型 - Model that has_many other model more than once accepts_nested_attributes_for has_many:通过创建和删除联接模型对象,具体取决于其他模型 - accepts_nested_attributes_for has_many :through Create and delete join model objects, depending on other model 通过关联具有has_many的两个模型的Findind模型 - Findind model that belongs to two models with a has_many through association Rails mutlipe has_many通过不同的模型到单个模型 - Rails mutlipe has_many through different models to single model has_many通过表单列出另一个父级的每个记录 - has_many through form listing each record of the other parent 在has_many中,ActiveRecord关联的条件在哪里相互冲突? - Where conditions on ActiveRecord associations conflicting with each other in has_many through? 模型has_many AND has_many:通过一个? - Model has_many AND has_many :through in one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM