0

나는 Profile이고 그 사람은 has_many :ratings입니다.연결된 모델의 개체 수를 어떻게 쿼리합니까?

내가 찾고 싶은 건 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 레코드와 연결되어 있고 Profile 레코드의 수를 반환하고 1 개의 관련 개체를 평가하는 것입니다.

ActiveRecord로 어떻게 달성 할 수 있습니까? user793789의 제안에 따라

편집 한

노력이 더 질의 : 많은 백업 및 forthing 후

> Profile.includes(:ratings).where('ratings.count > 1').references(:ratings).count 
    (55.3ms) SELECT COUNT(DISTINCT "profiles"."id") FROM "profiles" LEFT OUTER JOIN "ratings" ON "ratings"."profile_id" = "profiles"."id" WHERE (ratings.count > 1) 
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: aggregate functions are not allowed in WHERE 
LINE 1: ...N "ratings"."profile_id" = "profiles"."id" WHERE (ratings.co... 
                  ^
: SELECT COUNT(DISTINCT "profiles"."id") FROM "profiles" LEFT OUTER JOIN "ratings" ON "ratings"."profile_id" = "profiles"."id" WHERE (ratings.count > 1) 

> Profile.joins(:ratings).where('ratings.count > 1').count 
    (40.4ms) SELECT COUNT(*) FROM "profiles" INNER JOIN "ratings" ON "ratings"."profile_id" = "profiles"."id" WHERE (ratings.count > 1) 
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: aggregate functions are not allowed in WHERE 
LINE 1: ...N "ratings"."profile_id" = "profiles"."id" WHERE (ratings.co... 
                  ^
: SELECT COUNT(*) FROM "profiles" INNER JOIN "ratings" ON "ratings"."profile_id" = "profiles"."id" WHERE (ratings.count > 1) 

답변

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

영업 이익의 편집 1

, 우리는 마침내에 정착 :

Profile.joins(:ratings).group('profiles.id').having('count(ratings.id) > 0').length 

하지만이 작업을 수행하는 더 간단한 방법이 있어야합니다.

+0

또는 Profile.joins (: ratings) .where ('ratings.count> 0'). 카운트 – user793789

+0

아니요 ... 저에게 맞지 않는 사람은 없습니다. 그들은 당신을 위해 일 했습니까? – marcamillion

+0

프로필 has_one 평점 또는 has_many 평점? – user793789