2015-04-05 65 views
0

有文章和评论。评论属于文章。我们的目标是让所有评论发布在发布的文章上。根据其他模型的条件获取记录

class Article < ActiveRecord::Base 
    has_many :comments 

    # published 
    def self.is_published 
    where(published: true) 
    end 

class Comment < ActiveRecord::Base 
    belongs_to :article 

    def method_name 
    # get all comments where article.is_published 
    end 
end 

我们使用的控制器:

@comments = Comment.method_name.order("created_at desc") 

回答

2

你可以用示波器做到这一点。利用ActiveRecord#merge以避免重复发表文章意味着什么的条件。

class Comment < ActiveRecord::Base 
    belongs_to :article 

    def self.published_only 
    joins(:article). 
     merge(Article.is_published) 
    end 
end 

使用它看起来像

@comments = Comment.published_only.order(created_at: :desc)