有文章和评论。评论属于文章。目标是在发布的文章上发布所有评论。
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")
答案 0 :(得分: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)