Search code examples
ruby-on-railsrubypostgresqlarelhstore

How can I use Squeel with hstore in Rails


I would like to use the Squeel gem (based on Arel) for my Rails app (v 3.2.6). My hstore column is called properties.

These work perfectly fine:

User.where{(firstname == 'Ryan') & (lastname == 'Bates')}
User.where{"properties @> ('male' => '1')"}

The second example is a plain Postgres query, because Squeel doesn't seem to support hstore functions.

These don't work:

User.where{"properties @> ('male' => '1')" & firstname == 'Ryan'}
User.where{("properties @> ('male' => '1')") & (firstname == 'Ryan')}

Error:

NoMethodError: undefined method `&' for "properties @> ('male' => '1')":String

I do understand the error, but I don't know how to capsule my hstore query. Is there a better way to build hstore queries with Squeel or Arel?


Solution

  • Squeel supports SQL literals by using backticks (`).

    Something like the following might work:

    Person.where{(id == my{@person.id}) & (`preferences @> send_me_junk_email=>yes`)}
    

    When using backticks Squeel will drop down a layer of abstraction and execute the SQL directly.

    http://erniemiller.org/2012/05/30/sql-literals-in-squeel-or-overriding-backticks-in-ruby/