ruby-on-rails - 排除属于置顶帖子的评论

标签 ruby-on-rails ruby

我有三个模型:帖子、问题和评论,其中帖子有很多问题,问题有很多评论(帖子也通过问题有很多评论)。我有一个如下所示的方法:

def home
  @post = Post.where(:top => true).limit(1)
  @comments = Comment.order("created_at desc")
end

问题是,我不希望 @comments 中的任何评论属于 @post 中的帖子。如何排除(通过问题)属于第一篇文章的评论?

最佳答案

只需使用 where.not 排除属于 @post 的注释即可:

@comments = Comment.order("created_at desc").where.not(post_id: @post.id)

有关 this blog post 中的 where.not 的更多信息.

正如下面评论中添加的OP,如果 PostComment 之间存在另一个模型(在本例中:Question),那么你可以执行以下操作:

@comments = Comment.order("created_at desc").where.not(question_id: @post.question_ids)

关于ruby-on-rails - 排除属于置顶帖子的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29993942/

相关文章:

ruby-on-rails - 如何在 heroku 上安装 mupdf?

ruby-on-rails - Carrierwave - 如果文件类型不在白名单上,则触发存在验证

ruby-on-rails - datetime_select 上的限制分钟列表

arrays - Ruby 中哪个更快, `arr += [x]` 或 `arr << x`

ruby - Shotgun 上的 Sinatra 和 Ruby 1.9.2 问题

ruby-on-rails - PG::UndefinedTable: 错误:关系 "events"不存在

mysql - 我可以在 ruby​​ on Rails 中使用存储过程吗?

ruby-on-rails - Rails 时区偏移量

ruby - linux 类似于 windows shell 中的行为-运行没有 "ruby"附加到命令的 ruby​​?

ruby - 如何从 ruby​​ 上的 CSV 文件读取特定单元格值并输出结果?