我只想抓一个帖子的某些评论:那些已发布的布尔值设置为TRUE。
现在,我只是在Post show动作上调用@post.comments.all
。
在Post.rb模型中创建一个方法(published_comments)对我来说感觉很难看;我觉得这样的代码属于Comment.rb模型。但后来我不确定如何从Post对象中调用。
此外,我非常喜欢belongs_to
为我提供的选项,例如counter_cache或eager loading。
我该如何解决这个问题?
答案 0 :(得分:3)
有很多方法可以处理这类事情。一种选择是将其定义为has_many
模型中Post
关联中的条件,但听起来您不喜欢这种方法:
class Post
has_many :comments, :conditions => { :published => true }
end
另一种选择是在评论模型中设置default_scope
:
class Comment
default_scope where(:published => true)
end
或者,您可以在评论中创建范围并致电@post.comments.published.all
:
class Comment
scope :published, where(:published => true)
end