一個字符has_many :conversations through: chats
,以及每個對話has_many :messages
。當我打電話給@character.conversations
時,我希望在創建屬於對話的最新消息時對話進行排序。這是怎麼編碼的?Rails,通過雙層關聯訂購集合
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
我加了你建議** ** conversation.rb的default_scope,但它似乎沒有以影響對話的順序,而是在每個對話內排序消息。我希望它自己訂購對話? – Bazley
@Bazley你可以做'@ character.conversations'併發布生成的** SQL **嗎?你可以在你的控制檯中試試這個,看看'ORDER BY messages.created_at DESC'子句。 – dp7