Skip to content

Commit

Permalink
Merge pull request #12643 from severin/pg_cast_json_on_write
Browse files Browse the repository at this point in the history
cast json values on write to be consistent with reading from the db.
  • Loading branch information
senny committed Oct 25, 2013
2 parents 0e918ea + c3606af commit dc8fac1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
15 changes: 15 additions & 0 deletions 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.

Expand Down
Expand Up @@ -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?

Expand Down
7 changes: 7 additions & 0 deletions activerecord/test/cases/adapters/postgresql/json_test.rb
Expand Up @@ -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

Expand Down

0 comments on commit dc8fac1

Please sign in to comment.