给出两个postgres表samples
和sample_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