首页 > 解决方案 > 在一定条件下根据相关模型的数量选择模型

问题描述

我有Post一个has_many :comments。假设Comment有以下字段:another_model_id. 我想选择有 2 到 5 条评论的帖子another_model_id = 10(例如)。我尝试了几种结构,但没有成功:(

我试过的例子:

# Invalid SQL syntax error
Post
  .joins(:comments)
  .select("count(comment.another_model_id = 10) as comments_count)
  .where("comments_count BETWEEN 2 AND 5")

我真的不知道在哪里挖。是否有可能在单个查询中实现?谢谢!

标签: sqlruby-on-railsruby-on-rails-3activerecord

解决方案


Post
  .joins(:comments)
  .where(comments: { another_model_id: 10 })
  .group('posts.id')
  .having('count(comments.id) > 2 AND count(comments.id) < 5')

推荐阅读