Suavocado
Suavocado

Reputation: 969

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.

Upvotes: 4

Views: 5790

Answers (2)

jvnill
jvnill

Reputation: 29599

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)

Upvotes: 11

Ashwin Yaprala
Ashwin Yaprala

Reputation: 2777

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)

Upvotes: 1

Related Questions