Manually parse HStore data in Rails 4

Today I needed to manually parse a string returned from the HStore with Rails 4. The fix is not as intuitive as I'd like it, so here's a note to myself and for anyone else who has a similar problem.

If you do some weird querying, and execute it with ActiveRecord::Base.connection.raw_connection.exec_params your HStore data will be returned as a string. With Rails 3 and the activerecord-postgres-hstore it was pretty easy to parse the HStore-encoded string:


Rails 4 has a native support for HStore, but it was a pain to find how to manually parse the HStore-encoded string. The trick is to include the ActiveRecord::ConnectionAdapters::PostgreSQLColumn::Cast in to a class and use the string_to_hstore method:

class HstoreDeserializer
  include ActiveRecord::ConnectionAdapters::PostgreSQLColumn::Cast
  def initialize(str)
    @str = str

  def parse

If you have a similar problem, hopefully this will help you.

Did you like this article?

If so, subscribe to mailing list and get notified when the new stuff gets posted

* indicates required
comments powered by Disqus