字符has_many :conversations through: chats
和每个对话has_many :messages
。当我拨打@character.conversations
时,我希望在创建属于该会话的最新消息时订购对话。这是怎么编码的?
character.rb
has_many :chats, foreign_key: "character_id",
has_many :conversations, through: :chats, source: :conversation
# order: "conversation.messages.last.created_at DESC" # doesn't work
conversation.rb
has_many :chats, foreign_key: "conversation_id"
has_many :characters, through: :chats, source: :character
has_many :messages
答案 0 :(得分:1)
您可以将default_scope
添加到 conversation.rb :
default_scope -> {includes(:messages).order('messages.created_at DESC')}
注意: default_scope
肯定会妨碍性能,因为当您访问任何对话时,查询将一直运行。更好的方法是创建一个单独的范围,您可以在需要时调用它。
答案 1 :(得分:0)
您可以为关系应用其他范围,即使它是多层的:
@character.conversations.joins(:messages).order('messages.created_at DESC')