【问题标题】:How to get a records that have a a certain number of attributes, dependent on the record?如何根据记录获取具有一定数量属性的记录?
【发布时间】:2017-02-24 20:10:54
【问题描述】:

我正在做一个项目,我有一组帖子,一个帖子有很多 cmets,一个帖子还有一个 cmets_last_checked 字段和一个 comment_checking_threshold 字段。我需要能够获得在 cmets_last_checked 日期和当前日期之间的 cmets 数量超过其 comment_checking_threshold 的帖子。我不太确定如何执行此操作,因为每个帖子的阈值和日期范围会有所不同。

我有一些类似的东西:

@posts.joins(:comments
     ).where(comments: { 'comments.created_at > posts.comments_last_checked' }
     ).group('posts.id'
     ).having('COUNT(comments.id) >= posts.comment_checking_threshold')

但是我似乎无法让它工作。任何帮助将不胜感激。

编辑

我现在将代码更新为:

@posts.joins(:comments
     ).where('comments.created_at > posts.last_review_date'
     ).group('posts.id'
     ).having('posts.review_threshold >= COUNT(comments.id)')

但是我现在在“有子句”中收到错误未知列“posts.review_threshold”

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    编辑

    尝试将查询更改为

    Post.joins(:comments)
      .where('comments.created_at BETWEEN posts.comments_last_checked AND ?', Time.now)
      .group('posts.id')
      .having('COUNT(comments.id) >= posts.comment_checking_threshold')
    

    注意:此查询是根据您给定的信息生成的。检查正确的列名

    【讨论】:

    • 您好,我已将代码更新为您的示例,但如果我运行它,查询会返回 #<:activerecord_relation:0x00000014380108>,但没有帖子。
    • 我在我的系统中尝试了同样的方法,它应该会给出正确的结果如果它不起作用,那么检查你的标准是否符合你想要的
    • 可能您在该日期范围内没有 cmets 或未达到阈值
    • 您好,再次感谢您的帮助。查询似乎适用于 group 子句,但是 having 子句在 'having 子句'中给出错误 Unknown column 'posts.comment_checking_threshold'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2010-09-11
    相关资源
    最近更新 更多