Rails “where” method to find parent by child attribute

一个人想着一个人 提交于 2019-12-10 09:27:43

问题


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.


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/32940206/rails-where-method-to-find-parent-by-child-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!