带有ActiveRecord的分组查询的having子句中的条件求和

时间:2017-01-16 09:55:06

标签: ruby-on-rails postgresql arel

给出两个postgres表samplessample_values

Table "public.samples"
Column   |            Type             |                      Modifiers
------------+-----------------------------+------------------------------------------------------
id         | integer                     | not null default nextval('samples_id_seq'::regclass)
created_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
Indexes:
"samples_pkey" PRIMARY KEY, btree (id)
Referenced by:
TABLE "sample_values" CONSTRAINT "fk_rails_501ff3bcb6" FOREIGN KEY (sample_id) REFERENCES samples(id)

Table "public.sample_values"
Column   |            Type             |                         Modifiers
------------+-----------------------------+------------------------------------------------------------
id         | integer                     | not null default nextval('sample_values_id_seq'::regclass)
value      | integer                     |
sample_id  | integer                     |
created_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
Indexes:
"sample_values_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"fk_rails_501ff3bcb6" FOREIGN KEY (sample_id) REFERENCES samples(id)

我想查询Sample的实例,其中所有关联的SampleValue行仅符合特定条件。

使用AR和原始sql的组合,查询如下:

ALLOWED_VALUES = [1,2,3]
Sample.joins(:sample_values).
    group('samples.id').
    having('SUM((sample_values.value in (?))::int) = COUNT(*)', ALLOWED_VALUES)

我想摆脱原始的sql然而,我无法使用Arel为having子句构造节点。

我尝试SampleValues.arel_table[:value].in(ALLOWED_VALUES).sum.eq(Arel.star.count),但会引发以下错误:

TypeError: no implicit conversion of Arel::Table into String

0 个答案:

没有答案