Using PostgreSQL hstore with Rails 4
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
within your 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 Hash.
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 arake db:schema:load. Usually, you enablehstorein a migration, but during development it’s very common to drop and recreate the database. Sincehstoreis now part of your schema, it will fail when you runrake db:schema:loadas the migration hasn’t run yet andhstoreis not enabled. This gist will fix that.