1

消息可以有多个评论:

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") }

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

例子:

如果存在以下消息:

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 月)。

4

2 回答 2

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
于 2011-08-10T14:01:24.693 回答
0

这不在我的脑海中,但我认为你可以这样做:

Message.joins(:comments).where(["comments.start_time > ? AND comments.end_time < ?", start_time, end_time]);
于 2011-08-10T13:40:14.507 回答