Rails 4 has native support for PostgreSQL hstore.
Sadly, the tutorials and documentation I could find online, only point to how to use them with Rails 3, and only mention there will be “native” support with Rails 4.
Luckily, using hstore in Rails 4 is as easy as it should be. Native support means native: nothing needs to be done.
While previously you would need something like:
serialize :properties, ActiveRecord::Coders::Hstore
ActiveRecord subclass, now you just need to create the field with the appropriate migration
class AddPropertiesToProduct < ActiveRecord::Migration def change add_column :products, :properties, :hstore end end
With this, the
Product class will automatically serialize
properties as to an
hstore and present it to you as a Ruby
Two additional tips:
- If you want the default value to be an empty hash, in the migration you need to specify it as
- I recommend using this gist or something similar, to enable the
hstoreextension when doing a
rake db:schema:load. Usually, you enable
hstorein a migration, but during development it’s very common to drop and recreate the database. Since
hstoreis now part of your schema, it will fail when you run
rake db:schema:loadas the migration hasn’t run yet and
hstoreis not enabled. This gist will fix that.