对a的最后一条记录进行排序有多个关系表轨并保留主表值

时间:2014-10-13 08:49:15

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

我有ticketshas_many ticket_messages。我需要对最后一个ticket_message的创建时间进行排序。我是这样做的:

Ticket.joins(:ticket_messages).where('ticket_messages.created_at = (SELECT MAX(ticket_messages.created_at) FROM ticket_messages WHERE ticket_messages.ticket_id = tickets.id)').order("ticket_messages.created_at #{asc_or_desc}")

这会过滤掉没有ticket_messages的门票。我想保留tickets并显示它们。我该怎么做?

我试过了:

Ticket.includes(:ticket_messages).order("MAX(ticket_messages.created_at)")

引发错误:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "ticket_messages"
LINE 1: SELECT "tickets".* FROM "tickets"   ORDER BY MAX(ticket_mess...
                                                         ^
: SELECT "tickets".* FROM "tickets"   ORDER BY MAX(ticket_messages.created_at)
(pry) output error: #<ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "ticket_messages"
LINE 1: SELECT "tickets".* FROM "tickets"   ORDER BY MAX(ticket_mess...
                                                         ^
: SELECT "tickets".* FROM "tickets"   ORDER BY MAX(ticket_messages.created_at)>

我也试过这个:

Ticket.joins(:ticket_messages).order("MAX(ticket_messages.created_at)")

这也会引发错误:

    Ticket Load (0.8ms)  SELECT "tickets".* FROM "tickets" INNER JOIN "ticket_messages" ON "ticket_messages"."ticket_id" = "tickets"."id"  ORDER BY MAX(ticket_messages.created_at)
PG::GroupingError: ERROR:  column "tickets.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT "tickets".* FROM "tickets" INNER JOIN "ticket_message...
               ^
: SELECT "tickets".* FROM "tickets" INNER JOIN "ticket_messages" ON "ticket_messages"."ticket_id" = "tickets"."id"  ORDER BY MAX(ticket_messages.created_at)
(pry) output error: #<ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "tickets.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT "tickets".* FROM "tickets" INNER JOIN "ticket_message...
               ^
: SELECT "tickets".* FROM "tickets" INNER JOIN "ticket_messages" ON "ticket_messages"."ticket_id" = "tickets"."id"  ORDER BY MAX(ticket_messages.created_at)>

1 个答案:

答案 0 :(得分:0)

您可以使用ascdesc分别按升序或降序对其进行排序

Ticket.includes(:ticket_messages).order("ticket_messages.created_at DESC")