2
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 

Rails:我怎样才能加载与实例排序方法的关联?

我想有一个实例方法,这样,我可以做@ 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 

但是,如果可能的话,我宁愿保留在数据库级别的排序。有关如何完成此任务的任何建议?谢谢。

+0

另一个问题是分页。如果有一个新闻室将拥有的Post模型,然后每个Post对象将拥有一个:blog_post,:quote_post等,会更有意义吗? – 2011-04-16 15:50:20

回答

1

尝试这样:

#app/models/newsroom.rb 

scope :ordered_posts, lambda { 
    includes(:blog_posts,:quote_posts) & BlogPost.order("created_at asc") & QuotePost.order("created_at asc") 
} 

AREL应该能够处理包括报价和博客文章的顺序。您可以通过在BlogPost和QuotePost模型中使用范围来按顺序对created进行排序,然后在Newsroom#ordered_posts方法中使用这些范围。

+0

感谢您的回复。需要稍微玩一下这个想法;我想要一个实例方法,这样我可以执行@ newsroom.posts.paginated。 – 2011-04-16 16:23:17

0

我结束了使用多态post模型。这似乎给我带来了额外的模型/表的微不足道的缺点。我使用委托将特定的属性getter方法交给正确的模型。

class Newsroom < ActiveRecord::Base 
    has_many :posts 
end 

class Post < ActiveRecord::Base 
    belong_to :blog_post, :polymorphic => true 

    delegate :title, :author, :etc, :to => :postable 
end 

class BlogPost < ActiveRecord::Base 
    has_one :post, :as => :postable 
end 
相关问题