sql - Rails - 获取不同的事件,按关联事件实例的开始日期排序

标签 sql ruby-on-rails postgresql ruby-on-rails-4

我已经花了几个小时浏览 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/

相关文章:

mysql - mysql 中一张表上有多个触发器

sql - 如何使用 Apex Oracle SQL 中另一个表的行值触发表行值的更新?

sql - 将对 Azure 中数据库架构的更改传播回 Visual Studio?

ruby-on-rails - 无法在 heroku 上使用 devise 登录,所有其他环境都可以

mysql - 我可以在 SQL 的 WHERE 子句中使用 SUM 函数的结果吗?

ruby-on-rails - 不允许用户在 ruby​​ on rails 中提交带有空字段的表单

ruby-on-rails - 嵌套路由和 form_for 和 NoMethodError

sql - Money 数据类型的平均值

sql - 间歇性地合并两个排序的结果

sql - 触发器-postgres