2015-04-05 66 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)