使用Rails按联接表值进行排序

时间:2014-02-14 14:56:52

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

我正在尝试根据连接表上的字段值对项目列表进行排序。这是我到目前为止所得到的:

FeaturedEvent.joins(:event).order('event.start_datetime').limit(5)

这对我来说是正确的,但是当它运行时,它会返回一个关于缺少FROM语句的Postgres错误:

PG::UndefinedTable: ERROR: missing FROM-clause entry for table "event" LINE 1: ...ts"."id" = "featured_events"."event_id" ORDER BY event.star... ^ : SELECT "featured_events".* FROM "featured_events" INNER JOIN "events" ON "events"."id" = "featured_events"."event_id" ORDER BY event.start_datetime LIMIT 5

我尝试了this post中关于将排序放在默认范围内的建议,但它出现了同样的错误 - 我猜它是Postgres的事情。

我该如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:3)

尝试

FeaturedEvent.includes(:event).order('events.start_datetime').limit(5)

在您的订单中,表名应该是真正的数据库表名。

我猜,表名必须是events

答案 1 :(得分:1)

您的表名是事件,因此您只需在事件中添加s

FeaturedEvent.joins(:event).order('events.start_datetime').limit(5)