Skip to content

Instantly share code, notes, and snippets.

@Electron-libre
Created November 7, 2013 07:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Electron-libre/7350792 to your computer and use it in GitHub Desktop.
Save Electron-libre/7350792 to your computer and use it in GitHub Desktop.
Include this snippet into your model in order to use hstore in array with postgres and rails 4.0 ( fix is pending on the rails side )
module PgArrayHstoreFix
def self.included(base)
base.class_eval do
before_save :serialize_array_hash
end
def serialize_array_hash
self.class.attribute_names.each do |attribute|
column_definition = self.column_for_attribute(attribute)
if column_definition.array && column_definition.type == :hstore
serialized_hstore_array = []
self.send(attribute.to_sym).each do |value|
serialized_hstore_array << value.to_s.gsub(/{|}/,'')
end
self.send("#{attribute}=".to_sym, serialized_hstore_array)
end
end
end
end
end
@lessless
Copy link

lessless commented Nov 7, 2013

cool, thank you!

@rpontes
Copy link

rpontes commented Jan 13, 2014

How I use this snippet?

@theworkerant
Copy link

Slap this file somewhere it will be loaded, like ./initializers Then do include PgArrayHstoreFix on your model. However, this patch doesn't quite do what we want. Nothing happens for deserialization so you just get key/value strings back instead of Ruby Hash objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment