如何查询关联模型上的对象数量?

时间:2016-11-05 02:07:53

标签: ruby-on-rails activerecord ruby-on-rails-5 active-record-query

我有一个Profilehas_many :ratings

我想要找的是与{1}}对象关联的评级记录超过1的对象的数量。

我尝试了以下内容无济于事:

Profile

> Profile.includes(:ratings).where('ratings.count > 0').count
   (38.2ms)  SELECT COUNT(*) FROM "profiles" WHERE (ratings.count > 0)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "ratings"
LINE 1: SELECT COUNT(*) FROM "profiles" WHERE (ratings.count > 0)
                                               ^
: SELECT COUNT(*) FROM "profiles" WHERE (ratings.count > 0)

注意我的> Profile.where('ratings.count > 1').count (28.1ms) SELECT COUNT(*) FROM "profiles" WHERE (ratings.count > 1) ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "ratings" LINE 1: SELECT COUNT(*) FROM "profiles" WHERE (ratings.count > 1) ^ : SELECT COUNT(*) FROM "profiles" WHERE (ratings.count > 1) 模型不包含名为ratings的列。我要做的是count与每个count记录关联的ratings个对象的数量,并返回超过profile的{​​{1}}个记录的数量对相关对象进行评级。

如何使用ActiveRecord实现这一目标?

修改1

每个用户尝试两次查询793789的建议:

Profile

1 个答案:

答案 0 :(得分:0)

def extendedString(string1, string2):
    if len(string1) == len(string2):
        return "".join(i for j in zip(string1, string2) for i in j)
    else:
        longer, shorter = (string1, string2) if len(string1) > len(string2) else (string2, string1)
        shorter = shorter + shorter[-1] * (len(longer) - len(shorter))
        return "".join(i for j in zip(shorter, longer) for i in j)

OP编辑1

经过多次支持和支持,我们终于确定了这一点:

Profile.includes(:ratings).where('ratings.count > 0').references(:ratings).count

但我觉得必须有一种更简单的方法来做到这一点。