【问题标题】:Select model based on amount of related models with certain conditions在一定条件下根据相关模型的数量选择模型
【发布时间】:2018-11-11 14:33:29
【问题描述】:

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

我尝试过的示例:

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

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

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:
    Post
      .joins(:comments)
      .where(comments: { another_model_id: 10 })
      .group('posts.id')
      .having('count(comments.id) > 2 AND count(comments.id) < 5')
    

    【讨论】:

      【解决方案2】:

      使用counter_cache 是您的场景的最佳实践:

      在您的Comment 模型中,您需要设置counter_cache

      belongs_to :post, counter_cache: true
      

      那么你可以简单地使用这个查询:

      Post.joins(:comments)
          .where(comments: { another_model_id: 10 })
          .where('comments_count > ? AND comments_count < ?', 2, 5)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-22
        • 1970-01-01
        • 1970-01-01
        • 2016-05-31
        • 2017-11-05
        • 1970-01-01
        • 2014-06-01
        • 1970-01-01
        相关资源
        最近更新 更多