1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Serialize JSON attribute value nil as SQL NULL, not JSON 'null'

Test: JSON attribute value nil can be used in where(attr: nil)

Add changelog entry
This commit is contained in:
Trung Duc Tran 2016-07-03 21:27:37 +02:00
parent 0bc196518a
commit 21675fdc44
4 changed files with 41 additions and 1 deletions

View file

@ -1,3 +1,7 @@
* Serialize JSON attribute value `nil` as SQL `NULL`, not JSON `null`
*Trung Duc Tran*
* Return `true` from `update_attribute` when the value of the attribute
to be updated is unchanged.

View file

@ -17,7 +17,11 @@ module ActiveRecord
end
def serialize(value)
::ActiveSupport::JSON.encode(value)
if value.nil?
nil
else
::ActiveSupport::JSON.encode(value)
end
end
def accessor

View file

@ -102,6 +102,22 @@ if ActiveRecord::Base.connection.supports_json?
assert_equal(["v0", { "k1" => "v1" }], x.payload)
end
def test_select_nil_json_after_create
json = JsonDataType.create(payload: nil)
x = JsonDataType.where(payload:nil).first
assert_equal(json, x)
end
def test_select_nil_json_after_update
json = JsonDataType.create(payload: "foo")
x = JsonDataType.where(payload:nil).first
assert_equal(nil, x)
json.update_attributes payload: nil
x = JsonDataType.where(payload:nil).first
assert_equal(json.reload, x)
end
def test_rewrite_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first

View file

@ -113,6 +113,22 @@ module PostgresqlJSONSharedTestCases
assert_equal(nil, x.payload)
end
def test_select_nil_json_after_create
json = JsonDataType.create(payload: nil)
x = JsonDataType.where(payload:nil).first
assert_equal(json, x)
end
def test_select_nil_json_after_update
json = JsonDataType.create(payload: "foo")
x = JsonDataType.where(payload:nil).first
assert_equal(nil, x)
json.update_attributes payload: nil
x = JsonDataType.where(payload:nil).first
assert_equal(json.reload, x)
end
def test_select_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first