Rails的“何处”通过子级属性查找父级的方法 [英] Rails "where" method to find parent by child attribute

查看:94
本文介绍了Rails的“何处”通过子级属性查找父级的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用,正在尝试根据子类的日期创建父类列表。

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

现在我有:

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

但是我收到错误。

没有这样的列:order_reminders.date

"no such column: order_reminders.date"

我确定我的问题出在我的查询中,但我不确定如何解决。

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

推荐答案

您需要使用引用 joins ,包括 eager_load 取决于您的需要。确定选择内容的最简单方法是转到文档/ api 并阅读它们。

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.

至于答案,如果 order_reminders 被定义为订单,只需使用 joins ,其中使用 INNER JOIN 默认值,这意味着如果没有 order_reminders ,它将不会返回 orders ,这很可能是您在搜索时想要的

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)

这篇关于Rails的“何处”通过子级属性查找父级的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆