Rails,通过双层关联收集订单

时间:2016-08-29 17:49:37

标签: ruby-on-rails

字符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

2 个答案:

答案 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')