ruby-on-rails - 有条件的 own_to : only comments for post with published flag set TRUE

标签 ruby-on-rails activerecord belongs-to

我只想获取帖子的某些评论:那些已发布的 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/

相关文章:

ruby-on-rails - Ruby on Rails 3,多个域的电子邮件验证?

php - 未定义的属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$name laravel 5.4

mysql - 加入一个表的搜索结果 "belongs_to"另一个

ruby-on-rails - 设计模式和企业设计模式有什么区别?

ruby - 向 ActiveRecord 模型添加可读的字段描述

mysql - TravisCI 上 ActiveRecord 到 MySQL 数据库的正确连接字符串是什么?

mysql - express js : Sequlize belongsto returns empty results

ruby-on-rails - 如何定义一个方法,有点像 'yield'(我的意思是,自动捕获 block )?

ruby-on-rails - 如何重新定义 ruby​​ 和 rails request.ip 和 request.remote_ip 方法?

ruby-on-rails - rails : difference between placing stylesheets under 'assets' vs. 'public'