【问题标题】:Rails: How to sort messages with comments?Rails:如何对带有评论的消息进行排序?
【发布时间】:2011-08-10 13:28:47
【问题描述】:

消息可以有多个 cmets:

class Message < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :message
end

以下命名范围返回在给定时间范围内创建的消息,按创建时间排序(最新在前):

scope :created_between, 
      lambda { |rng| where("created_at" => (rng[:start_time]..rng[:end_time])).
                     order("created_at DESC") }

我如何编写一个命名范围来返回具有在给定时间范围内创建的帖子(消息本身或其一个 cmets)的消息,按最新帖子的创建时间排序(最新的在前)?

例子:

如果存在以下消息:

Message 1            April, 2010
  Comment 1          May, 2011
  Comment 2          July 2011
Message 2            January 2011
  Comment 1          August 2011
  Comment 2          March 2011
  Comment 3          February 2011
Message 3            March 2009
  Comment 1          January 2010
Message 4            June 2011

然后

scope :has_post_between({:start_time => <February 2010>, 
                         :end_time => <August 2011>}), ...

应该返回:

Message 2
Message 1
Message 4

Message 3 不包括在内,因为它的帖子是在 2010 年 2 月之前创建的。 Message 2 是第一位的,因为它有最新的帖子(2011 年 8 月)。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 active-relation active-record-query


    【解决方案1】:
    class Message < ActiveRecord::Base
      has_many :comments
    
      scope :updated_between, lambda { |rng|
        joins(:comments).
        where(:created_at => rng, :comments => { :created_at => rng }).
        order("comments.created_at DESC, messages.created_at DESC")
      }
    end
    

    【讨论】:

      【解决方案2】:

      这不是我的想法,但我认为你可以做到:

      Message.joins(:comments).where(["comments.start_time > ? AND comments.end_time < ?", start_time, end_time]);
      

      【讨论】:

      • 你没有考虑到消息本身。
      猜你喜欢
      • 1970-01-01
      • 2013-09-14
      • 2020-05-04
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      相关资源
      最近更新 更多