开发者

Conditional belongs_to: only comments for post with published flag set TRUE

开发者 https://www.devze.com 2023-02-12 03:03 出处:网络
I\'d like to grab only certain comments for a post: those that have a published boolean set TRUE. Right now, I simply call a @post.comments.all on the Post show action.

I'd like to grab only certain comments for a post: those that have a published boolean set TRUE.

Right now, I simply call a @post.comments.all on the Post show action.

Creating a method (published_comments) in the Post.rb model feels ugly to me; I have the feeling such code belongs开发者_运维技巧 in the Comment.rb model. But then I am not sure how to call if from within a Post object.

Moreover, I really like the options that belongs_to offers me, such as the counter_cache or eager loading.

How should I solve this?


There's a whole bunch of ways to deal with this kind of thing. One option is to define it as a condition in the has_many association in the Post model, but it sounds like you don't like this approach:

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

Another option is to set the default_scope in the Comment model:

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

Or, you could create a scope in comment and call @post.comments.published.all:

class Comment
  scope :published, where(:published => true)
end
0

精彩评论

暂无评论...
验证码 换一张
取 消