Skip to content
Browse files

Merge pull request #12643 from severin/pg_cast_json_on_write

cast json values on write to be consistent with reading from the db.
  • Loading branch information...
2 parents 0e918ea + c3606af commit dc8fac1cacb120dc2535b67bdd6436d220901c7a @senny senny committed Oct 25, 2013
View
15 activerecord/CHANGELOG.md
@@ -1,3 +1,18 @@
+* Type cast json values on write, so that the value is consistent
+ with reading from the database.
+
+ Example:
+
+ x = JsonDataType.new tags: {"string" => "foo", :symbol => :bar}
+
+ # Before:
+ x.tags # => {"string" => "foo", :symbol => :bar}
+
+ # After:
+ x.tags # => {"string" => "foo", "symbol" => "bar"}
+
+ *Severin Schoepke*
+
* `ActiveRecord::Store` works together with PG `hstore` columns.
Fixes #12452.
View
4 activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
@@ -249,6 +249,10 @@ def type_cast(value)
end
class Json < Type
+ def type_cast_for_write(value)
+ ConnectionAdapters::PostgreSQLColumn.json_to_string value
+ end
+
def type_cast(value)
return if value.nil?
View
7 activerecord/test/cases/adapters/postgresql/json_test.rb
@@ -49,6 +49,13 @@ def test_change_table_supports_json
JsonDataType.reset_column_information
end
+ def test_cast_value_on_write
+ x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar}
+ assert_equal({"string" => "foo", "symbol" => "bar"}, x.payload)
+ x.save
+ assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload)
+ end
+
def test_type_cast_json
assert @column

0 comments on commit dc8fac1

Please sign in to comment.
Something went wrong with that request. Please try again.