我只想获取帖子的某些评论:那些已发布的 bool 值设置为 TRUE 的评论。
现在,我只需在 Post show 操作上调用 @post.comments.all
即可。
在 Post.rb 模型中创建一个方法 (published_comments) 对我来说感觉很难看;我感觉这样的代码属于 Comment.rb 模型。但随后我不确定如何从 Post 对象中调用 if 。
此外,我真的很喜欢 belongs_to
为我提供的选项,例如 counter_cache 或预加载。
我该如何解决这个问题?
最佳答案
有很多方法可以处理这种事情。一种选择是将其定义为 Post
模型中 has_many
关联中的条件,但听起来您不喜欢这种方法:
class Post
has_many :comments, :conditions => { :published => true }
end
另一个选项是在 Comment 模型中设置 default_scope
:
class Comment
default_scope where(:published => true)
end
或者,您可以在评论中创建一个范围并调用@post.comments.published.all
:
class Comment
scope :published, where(:published => true)
end
关于ruby-on-rails - 有条件的 own_to : only comments for post with published flag set TRUE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5065337/