简体   繁体   中英

Rails “where” method to find parent by child attribute

I have a Rails app where I'm trying to create a list of parent classes based on the date of their child classes.

right now I have:

orders = Order.where("order_reminders.date < ?", 1.month.from_now)

But I'm receiving an error.

"no such column: order_reminders.date"

I'm sure my problem is with my query but I'm not sure how to fix it.

You need to use methods like references , joins , includes or eager_load depending on what you need. The simplest way to determine what to select is to go to the documentation/api and read them.

As for the answer, if order_reminders is defined as an association in Order , just use joins which uses an INNER JOIN by default, meaning it won't return orders without order_reminders which is most probably what you want when you're searching for something.

Order.joins(:order_reminders).where('order_reminders.date < ?', 1.month.from_now)

Is order_reminders another table in your app?

If order has_many order_reminders then try this query

Order.joins(:order_reminders).where("order_reminders.date < ?", 1.month.from_now)

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