简体   繁体   中英

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. Types has_many SaleTypes, has_many Sales through SalesTypes.

I want to find all Sales where Types.id == 1 OR is in [1, 2, 3].

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)

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