【问题标题】:Sorting conversations with belongs_to/has_many relationship使用 belongs_to/has_many 关系对对话进行排序
【发布时间】:2016-06-08 07:12:37
【问题描述】:

我有以下型号:

class Post < ActiveRecord::Base
  has_many :conversations
end


class Conversation < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
  has_many :messages
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end

所以有帖子,每个帖子可以有很多对话。在每个对话中都有许多消息。到目前为止一切顺利。

现在我想显示用户所有对话的概览。看来我无法让它按我想要的方式工作:

获取当前用户拥有的所有对话 (current_user.conversations) 根据他们 belong_to 的帖子 ID 对所有对话进行分组,并按日期对该组进行排名 -> 包含最新消息的(对话)组应显示在顶部。这是我到目前为止的屏幕截图。

所有的合作都应该按照他们在任何时候所属的帖子进行分组。如果任何对话中包含新消息,则整个对话组应移至视图顶部,而不仅仅是包含新消息的对话。这就是我无法工作的原因。

上面的截图是用以下代码制作的:

current_user.conversations.includes(:messages, post: :user).order("posts.id DESC, messages.created_at DESC").to_a.paginate( :page => params[:page], :per_page => 10 )

正如您在屏幕截图中看到的那样,对话按帖子 ID 分组。但是第二组应该出现在第一组上方,因为第二组中的对话包含最新消息。

感谢任何帮助。非常感谢!

【问题讨论】:

  • 因为你是先由posts.id订购的,posts.id DESC, messages.created_at DESC
  • @lusketeer 由messages.created_at 排序首先破坏了post.id 的分组——这才是真正的问题。假设某人在特定对话中发送了一条新消息-> 然后该特定对话排在首位。但是所有其他对话(属于同一个帖子)保持在同一个位置。我想要实现的是,属于同一个帖子的所有对话都排在首位。

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


【解决方案1】:

你的方法行不通的原因,就像@lusketeer 在问题下评论的那样:

because you ordered by `posts.id` first

解决方案应该是先对帖子进行分组,然后加载对话和消息并按消息时间戳排序:

# Add the association between user and post
class User < ActiveRecord::Base
  has_many: :participated_posts, through: :conversation, class: "Post"
  ...
end

current_user.participated_posts.includes(conversations: [:messages, :user]).order("messages.created_at DESC")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-24
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    相关资源
    最近更新 更多