2

我只想获取帖子的某些评论:那些具有已发布布尔集 TRUE 的评论。

现在,我只是简单地调用一个@post.comments.allon the Post show 动作。

在 Post.rb 模型中创建一个方法(published_comments)对我来说很难看;我觉得这样的代码属于 Comment.rb 模型。但是我不确定如何从 Post 对象中调用 if 。

此外,我真的很喜欢belongs_to为我提供的选项,例如 counter_cache 或急切加载。

我应该如何解决这个问题?

4

1 回答 1

3

有很多方法可以处理这种事情。一种选择是将其定义为模型中has_many关联中的条件Post,但听起来您不喜欢这种方法:

class Post
  has_many :comments, :conditions => { :published => true }
end

另一种选择是default_scope在 Comment 模型中设置:

class Comment
  default_scope where(:published => true)
end

或者,您可以在评论中创建一个范围并调用@post.comments.published.all

class Comment
  scope :published, where(:published => true)
end
于 2011-02-21T11:53:57.647 回答