使用 Arel 和数组属性在 Rails 中构建查询的问题

Issue constructing a query in Rails using Arel and array attributes

我遇到了检查两个数组是否具有一个或多个共同元素的查询。

由于查询是更大查询的一部分,因此我需要使用 Arel 来完成此操作。但是 && 运算符,称为重叠运算符,在 Arel gem.

中没有实现

有一个 postgres_ext gem 实现了上述运算符并提供了一个 .overlap 方法,因此可以构建类似于我所做的查询:DiscountCondition.arel_table[:target_plan_period_ids].overlap(target_period_ids)。这会产生一个 SQL where 子句,对我来说效果很好:"\"discount_conditions\".\"target_plan_period_ids\" && '{2}'".

但是。问题是我们的应用程序中的某些测试因以下错误而失败:NoMethodError: undefined method 'array' for #<ActiveRecord::ConnectionAdapters::SQLite3Column:0x007f23c4995ba8>(原来 gem 与某些适配器不兼容)。

一个简单的 ActiveRecord 有效查询是 DiscountCondition.where('target_plan_period_ids && ARRAY[?]', target_period_ids),它生成以下 SQL 查询 "SELECT \"discount_conditions\".\"discount_id\" FROM \"discount_conditions\" WHERE (target_plan_period_ids && ARRAY[2])".

所以,我想知道是否有人遇到过这个问题并成功解决了这个问题。

以防万一有人遇到同样的问题,我最终 monkey patching the aforementioned functionalitypostgres_ext gem 进入项目。