[英]How do I order records based on associated records
class Conversation < ApplicationRecord
has_many :messages, dependent: :destroy
belongs_to :organization
has_one :latest_message, -> {
order(created_at: :desc)
}, class_name: "Message", foreign_key: "conversation_id"
end
class Message < ApplicationRecord
belongs_to :conversation
end
How do I order conversation list with the latest_message created_at time.如何使用 latest_message created_at 时间订购对话列表。
I tried我试过了
conversations.order("latest_message.created_at desc").to_a
but I'm getting the error但我得到了错误
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "latest_message"
12:33:07 web.1 | LINE 1: ...E "conversations"."organization_id" = $1 ORDER BY latest_mes...
12:33:07 web.1 | ^
12:33:07 web.1 |
12:33:07 web.1 | from /home/rafi/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activerecord-6.0.2.2/lib/active_record/connection_adapters/postgresql_adapter.rb:672:in `exec_params'
12:33:07 web.1 | Caused by PG::UndefinedTable: ERROR: missing FROM-clause entry for table "latest_message"
12:33:07 web.1 | LINE 1: ...E "conversations"."organization_id" = $1 ORDER BY latest_mes...
12:33:07 web.1 | ^
possibly because the latest message is not a present in DB;可能是因为 DB 中不存在最新消息; but only in the model.但仅限于 model。
In ActiveRecord the arguments to .where
, .group
and .order
need to be the actual table names and not associations as they generate SQL.在 ActiveRecord 中, .where
到 .where 、 .group
和.order
需要是实际的表名而不是关联,因为它们会生成 SQL。
You don't really need that association at all though:但是,您根本不需要该关联:
Conversation.joins(:messages)
.group(:id)
.order("MAX(messages.created_at) DESC")
You may need to use .group('conversations.id')
on some drivers like TinyTDS that will produce an ambiguous GROUP BY id
query instead of GROUP BY "conversations"."id"
.您可能需要在某些驱动程序(如 TinyTDS)上使用.group('conversations.id')
,这将产生一个模棱两可的GROUP BY id
查询而不是GROUP BY "conversations"."id"
。 If you want to include conversations that don't have any messages use left_joins
:如果您想包含没有任何消息的对话,请使用left_joins
:
Conversation.left_joins(:messages)
.group(:id)
.order("MAX(messages.created_at) DESC")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.