Don't error when invalid json is assigned to a JSON column

Keeping with our behavior elsewhere in the system, invalid input is
assumed to be `nil`.

Fixes #18629.
This commit is contained in:
Sean Griffin 2015-01-21 11:47:11 -07:00
parent 14599a5758
commit e8460f8bbe
3 changed files with 15 additions and 1 deletions

View File

@ -1,3 +1,9 @@
* Invalid values assigned to a JSON column are assumed to be `nil`.
Fixes #18629.
*Sean Griffin*
* Add `ActiveRecord::Base#accessed_fields`, which can be used to quickly
discover which fields were read from a model when you are looking to only
select the data you need from the database.

View File

@ -11,7 +11,7 @@ module ActiveRecord
def type_cast_from_database(value)
if value.is_a?(::String)
::ActiveSupport::JSON.decode(value)
::ActiveSupport::JSON.decode(value) rescue nil
else
super
end

View File

@ -179,6 +179,14 @@ module PostgresqlJSONSharedTestCases
assert_equal({ 'one' => 'two', 'three' => 'four' }, json.payload)
assert_not json.changed?
end
def test_assigning_invalid_json
json = JsonDataType.new
json.payload = 'foo'
assert_nil json.payload
end
end
class PostgresqlJSONTest < ActiveRecord::TestCase