有条件的belongs_to:仅对已发布标志设置为TRUE的帖子发表评论
我只想获取帖子的某些评论:那些已发布的布尔集为 TRUE 的评论。
现在,我只需在 Post show 操作上调用 @post.comments.all
即可。
在 Post.rb 模型中创建一个方法 (published_comments) 对我来说感觉很难看;我感觉这样的代码属于 Comment.rb 模型。但随后我不确定如何从 Post 对象中调用 if 。
此外,我真的很喜欢 belongs_to
为我提供的选项,例如 counter_cache 或预加载。
我应该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有很多方法可以处理这种事情。一种选择是将其定义为
Post
模型中has_many
关联中的条件,但听起来您不喜欢这种方法:另一种选择是设置评论模型中的
default_scope
:或者,您可以在评论中创建一个范围并调用
@post.comments.published.all
: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 thePost
model, but it sounds like you don't like this approach:Another option is to set the
default_scope
in the Comment model:Or, you could create a scope in comment and call
@post.comments.published.all
: