class Newsroom < ActiveRecord::Base
has_many :blog_posts
has_many :quote_posts
end
class BlogPost < ActiveRecord::Base
belongs_to :newsroom
end
class QuotePost < ActiveRecord::Base
belongs_to :newsroom
end
我想有一个实例方法,这样,我可以做@ newsroom.posts度日created_at分类blog_posts和quote_posts的集合。
def posts
@posts ||= #load and sort blog_posts, quote_posts, etc
end
什么是最好和最有效的方法来实现这一目标?我研究过使用default_scope,如下所示:
default_scope :include => [:blog_posts, :quote_posts]
def posts
@posts ||= [blog_posts + quote_posts].flatten.sort{|x,y| x.created_at <=> y.created_at}
end
但是,如果可能的话,我宁愿保留在数据库级别的排序。有关如何完成此任务的任何建议?谢谢。
另一个问题是分页。如果有一个新闻室将拥有的Post模型,然后每个Post对象将拥有一个:blog_post,:quote_post等,会更有意义吗? – 2011-04-16 15:50:20