Search code examples
ruby-on-railsarelrails-postgresql

Issue constructing a query in Rails using Arel and array attributes


I'm stuck with the query that checks whether two arrays have one or more elements in common.

Since the query is the part of a much bigger query, I need to use Arel to accomplish this. But the && operator, known as the overlap operator, is not implemented in Arel gem.

There's a postgres_ext gem that implements the above mentioned operator and provides a .overlap method so that one could construct the query similar to the one I did: DiscountCondition.arel_table[:target_plan_period_ids].overlap(target_period_ids). This produces an SQL where clause that works fine for me: "\"discount_conditions\".\"target_plan_period_ids\" && '{2}'".

But. The thing is some tests in our application failed with the following error: NoMethodError: undefined method 'array' for #<ActiveRecord::ConnectionAdapters::SQLite3Column:0x007f23c4995ba8> (turns out the gem is incompatible with some adapters).

A simple ActiveRecord query that works is DiscountCondition.where('target_plan_period_ids && ARRAY[?]', target_period_ids) that produces the following SQL query "SELECT \"discount_conditions\".\"discount_id\" FROM \"discount_conditions\" WHERE (target_plan_period_ids && ARRAY[2])".

So, I wanted to know if anyone faced that issue and succeeded to workaround this.


Solution

  • Just in case someone ever faces the same issue, I ended up monkey patching the aforementioned functionality of a postgres_ext gem into the project.