Search code examples
ruby-on-railspostgresqlrails-activerecordhstore

Rails/Postgres How to query hstore value if it contains value of passed array


I'm using Postgres with hstore in my Rails project. I store address information (street, city, postcode, country,...) in an hstore column called "address". I can query the database for a certain city like this:

Company.where("address -> 'country' = 'Finland'")

Works perfectly.

What I would like to do is querying the database for an array of countries like this:

Company.where("address -> 'country' IN my_array_of_many_countries")

Of course it's not working that way. Does anyone know how I can get all Companies from countries stored in my my_array_of_many_countries array?

Any help is highly appreciated.


Solution

  • The easiest solution would be to transform you array into a string:

    my_array_of_many_countries = ['France', 'Germany']
    my_array_of_many_countries_string = "'#{my_array_of_many_countries.join("','")}'"
    Company.where("address -> 'country' IN (#{my_array_of_many_countries_string})")
    

    This would only work if your array only contain strings. Btw, Haven't tested it.