简体   繁体   中英

Finding table records based on another table column

I have two tables:

Orders => [state]
Ads => [title, order_id]

Order has_many Ads
Ad belongs_to Order

If I want to find all orders with ads that the title is "AAA" I do:

Order.all.joins(:ad).where(title: "AAA")

But I want to find all ads where the orders' state attribute is equals to "XXX". How can I do this ?

In rails you can do it like this:

Ad.joins(:order).where(orders: { state: "AAA" })

This will produce the following SQL:

SELECT ads.*
FROM ads
INNER JOIN orders ON order.id = ads.order_id
WHERE orders.state = 'AAA'

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