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
rake db:migrate
rails g migration AddPropertiesToChocolate
class AddPropertiesToChocolate < ActiveRecord::Migration
def change
add_column :chocolates, :properties, :hstore
end
end
rake db:migrate

Rails console:

p = Chocolate.last
p.properties = {'color' => 'orange'}
p.properties['price'] = '5'
p.save
Chocolate.where("properties -> 'color' = 'orange' ")
Chocolate.where("properties -> '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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top