我已经花了几个小时浏览 StackOverflow 并研究这个查询,但仍然无法正常工作!希望这里的 SO 专家可以让痛苦消失......
我有两个模型,Event 和 EventInstance。一个事件有_许多事件实例。
我想做的是轻松获取事件列表(不是 EventInstances),其中:
- 事件不同且不重复
- 事件按最近的 EventInstance 的开始日期排序
- 事件实例具有属性 :active => true
- 只返回开始日期在未来的事件实例
我目前有查询
Event.joins(:event_instances).select('distinct events.*').where('event_instances.start_date >= ?', Time.now).where('event_instances.active = true')
这将返回一个事件列表,但不按日期排序。太棒了 - 所以我快到了!
如果我更改查询以在末尾添加:
.order('event_instances.start_date')
我得到错误:
PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
所以我把它移到了select语句中:
select('distinct event_instances.start_date, events.*')
现在我明白了
PG::UndefinedFunction: ERROR: function count(date, events) does not exist
我试过移动方法,使用 include,一切,但我仍然无法让它工作。任何帮助将非常感激!谢谢。
最佳答案
尝试改变
.order('event_instances.start_date')
到
.order(:event_instances.start_date)
或者如果您需要降序,请将 .reverse_order
方法添加到查询的末尾
关于sql - Rails - 获取不同的事件,按关联事件实例的开始日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290310/