我有三个模型:帖子、问题和评论,其中帖子有很多问题,问题有很多评论(帖子也通过问题有很多评论)。我有一个如下所示的方法:
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,如果 Post
和 Comment
之间存在另一个模型(在本例中:Question
),那么你可以执行以下操作:
@comments = Comment.order("created_at desc").where.not(question_id: @post.question_ids)
关于ruby-on-rails - 排除属于置顶帖子的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29993942/