1

Does somoone knows if it is possible to have array of hstore in rails 4 ? i tryied with

add_column :orders, :frozen_content, :hstore , array: true

but i got

 PG::Error: ERROR:  malformed array literal: 

when i try to save

3 Answers 3

3

In principle, yes, but as you've found it isn't being escaped correctly when saved. I've just today logged an issue about that, see https://github.com/rails/rails/issues/11135 (includes a fix patch and some demo code)

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure if this is the same issue. At least, I managed to fix this bug using this other patch: github.com/rails/rails/pull/11477
2

This is a bug that exists at least in Rails 4.0.1 .

A pull request was proposed to fix it, but until it is merged you can monkey-patch Rails:

# config/initializers/extensions/postgres.rb
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLColumn < Column
      module Cast
        private

          def quote_and_escape(value)
            case value
            when "NULL"
              value
            else
              "\"#{value.gsub(/(["\\])/, '\\\\\1')}\""
            end
          end
      end
    end
  end
end

Sidenote, I had trouble testing this in the Rails console because the initializer wasn't getting loaded there. You can do so with:

load "#{Rails.root}/config/initializers/extensions/postgres.rb"

1 Comment

The bug is still present in Rails 4.0.2. Hopefully they merge it soon!
0

You can sue the activerecord-postgres-hstore gem:

https://github.com/engageis/activerecord-postgres-hstore

From the docs:

  1. Create a hstore-backed field:

    class Person < ActiveRecord::Base serialize :data, ActiveRecord::Coders::Hstore end

  2. Add fields to to it:

    person = Person.new person.data['foo'] = 'bar' person.save

  3. Query it:

    Perosn.where("data -> 'foo' = 'bar'")

Railscast #345 (which is behind a paywall) covers using hstore in more details, using the activerecord-postgres-hstore gem:

http://railscasts.com/episodes/345-hstore

Note: I haven't tried it with rails 4... YMMV.

1 Comment

i was trying to do HSTORE Array here. With classic Hstore column i have no problems

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.