Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

PostgreSQL hstore types are automatically deserialized from the datab…

…ase.
  • Loading branch information...
commit 776af48acb1035e70a326609ec5e5b632ef0c2c5 1 parent 8cb7bc8
@tenderlove tenderlove authored
View
4 activerecord/CHANGELOG.md
@@ -1,3 +1,7 @@
+## Rails 4.0.0 (unreleased) ##
+
+* PostgreSQL hstore types are automatically deserialized from the database.
+
## Rails 3.2.0 (unreleased) ##
* Added ability to run migrations only for given scope, which allows
View
2  activerecord/lib/active_record/connection_adapters/column.rb
@@ -83,6 +83,7 @@ def type_cast(value)
when :date then klass.value_to_date(value)
when :binary then klass.binary_to_string(value)
when :boolean then klass.value_to_boolean(value)
+ when :hstore then klass.cast_hstore(value)
else value
end
end
@@ -100,6 +101,7 @@ def type_cast_code(var_name)
when :date then "#{klass}.value_to_date(#{var_name})"
when :binary then "#{klass}.binary_to_string(#{var_name})"
when :boolean then "#{klass}.value_to_boolean(#{var_name})"
+ when :hstore then "#{klass}.cast_hstore(#{var_name})"
else var_name
end
end
View
4 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -49,6 +49,10 @@ def string_to_time(string)
super
end
end
+
+ def cast_hstore(string)
+ Hash[[string.split('=>').map { |k| k[1...-1] }]]
+ end
end
# :startdoc:
View
16 activerecord/test/cases/adapters/postgresql/hstore_test.rb
@@ -21,4 +21,20 @@ def test_column
assert column
assert_equal :hstore, column.type
end
+
+ def test_type_cast_hstore
+ column = Hstore.columns.find { |c| c.name == 'tags' }
+ assert column
+
+ data = "\"1\"=>\"2\""
+ hash = column.class.cast_hstore data
+ assert_equal({'1' => '2'}, hash)
+ assert_equal({'1' => '2'}, column.type_cast(data))
+ end
+
+ def test_select
+ @connection.execute "insert into hstores (tags) VALUES ('1=>2')"
+ x = Hstore.find :first
+ assert_equal({'1' => '2'}, x.tags)
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.