Merge pull request #41677 from anilmaurya/fix-41521

Fixes #41521, ActiveModel::Dirty fails on to_json
This commit is contained in:
Rafael França 2021-06-24 14:10:29 -04:00 committed by GitHub
commit 637d386fbb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 0 deletions

View File

@ -1,3 +1,9 @@
* Fix `to_json` for `ActiveModel::Dirty` object.
Exclude +mutations_from_database+ attribute from json as it lead to recursion.
*Anil Maurya*
* Add `ActiveModel::AttributeSet#values_for_database`
Returns attributes with values for assignment to the database.

View File

@ -140,6 +140,11 @@ module ActiveModel
@mutations_from_database = nil
end
def as_json(options = {}) # :nodoc:
options[:except] = [options[:except], "mutations_from_database"].flatten
super(options)
end
# Clears dirty data and moves +changes+ to +previous_changes+ and
# +mutations_from_database+ to +mutations_before_last_save+ respectively.
def changes_applied

View File

@ -1,6 +1,7 @@
# frozen_string_literal: true
require "cases/helper"
require "active_support/json"
class DirtyTest < ActiveModel::TestCase
class DirtyModel
@ -237,4 +238,19 @@ class DirtyTest < ActiveModel::TestCase
test "model can be dup-ed without Attributes" do
assert @model.dup
end
test "to_json should work on model" do
@model.name = "Dmitry"
assert_equal "{\"name\":\"Dmitry\",\"color\":null,\"size\":null,\"status\":\"initialized\"}", @model.to_json
end
test "to_json should work on model with :except string option " do
@model.name = "Dmitry"
assert_equal "{\"color\":null,\"size\":null,\"status\":\"initialized\"}", @model.to_json(except: "name")
end
test "to_json should work on model with :except array option " do
@model.name = "Dmitry"
assert_equal "{\"color\":null,\"size\":null,\"status\":\"initialized\"}", @model.to_json(except: ["name"])
end
end