Using Hstore in Rails 4 with PostgreSQL

Hstore basically gives you a schema-less data store in your PostgreSQL DB. This allows you to store the Hash in a Database column.

If you want to query Model records, it is very difficult if you use Serialize to store dynamic attributes. Hstore acts same as Serialize but we can additionally query the model records using Hstore.

Please follow below steps to enable Hstore in a Ruby on Rails 4 application.

rails generate migration enable_hstore_extension
class EnableHstoreExtension < ActiveRecord::Migration
  def change
    enable_extension 'hstore'
  end
end
&#91;/ruby&#93;

<pre>rake db:migrate</pre>

<pre>rails g migration AddPropertiesToChocolate</pre>

[ruby]
class AddPropertiesToChocolate < ActiveRecord::Migration
  def change
    add_column :chocolates, :properties, :hstore
  end
end
&#91;/ruby&#93;

<pre>rake db:migrate</pre>

<strong>Rails console:</strong>

[ruby]
p = Chocolate.last
p.properties = {'color' =&gt; 'orange'}
p.properties['price'] = '5'
p.save
Chocolate.where("properties -&gt; 'color' = 'orange' ")
Chocolate.where("properties -&gt; 'price' ='5' ")

Finally, you can define accessors for your Hstore keys in your model. Validations work just like they would for any other column in your model.

class Chocolate < ActiveRecord::Base
  # setup hstore
  store_accessor :properties, :color

  # can even run typical validations on hstore fields
  validates :color,
  inclusion: { in: %w{orange gold red} }

end