Reputation: 223
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
Upvotes: 1
Views: 1572
Reputation: 19203
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"
Upvotes: 2
Reputation: 3779
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)
Upvotes: 3
Reputation: 4199
You can sue the activerecord-postgres-hstore gem:
https://github.com/engageis/activerecord-postgres-hstore
From the docs:
Create a hstore-backed field:
class Person < ActiveRecord::Base serialize :data, ActiveRecord::Coders::Hstore end
Add fields to to it:
person = Person.new person.data['foo'] = 'bar' person.save
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.
Upvotes: 0