Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 942
Suavocado Avatar asked Dec 14 '22 11:12

Suavocado


2 Answers

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)
like image 144
jvnill Avatar answered Jan 06 '23 23:01

jvnill


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)
like image 29
Ashwin Yaprala Avatar answered Jan 06 '23 23:01

Ashwin Yaprala