Search code examples
ruby-on-railsrubypostgresqlruby-on-rails-4hstore

select single property in hstore field with Rails 4.1


I am using Postgres 9.3 with Rails 4.1.

Suppose I have a table with a properties hstore colum.

I now want to select a single key inside the hstore column in a scope (or somewhere else..)

What I tried: Model.select("properties -> 'category'")

What happens: Rails gives me an array like this:

[#<Model id: nil>,
 #<Model id: nil>,
 #<Model id: nil>,
 #<Model id: nil>]

What I want:

[#<Model id: nil, category: 'foo'>,
 #<Model id: nil, category: 'bar'>,
 #<Model id: nil, category: 'baz'>,
 #<Model id: nil, category: 'foo'>]

Solution

  • Try:

    =>  Model.where("properties @> hstore(?, ?)", 'key', 'value').select(:category)
    => [#<Model id: nil, category: 'foo'>]