消息可以有多个评论:
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 月)。