如何获取具有一定数量属性的记录,具体取决于记录?

时间:2017-02-24 11:14:09

标签: ruby-on-rails ruby activerecord

我正在开展一个项目,我有一组帖子,帖子有很多评论,帖子还有一个comments_last_checked字段和一个comment_checking_threshold字段。我需要能够在comments_last_checked日期和当前日期之间获得比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)')

但是我现在在'having clause'中得到错误未知列'posts.review_threshold'

1 个答案:

答案 0 :(得分:0)

修改

尝试将查询更改为

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')
  

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