Skip to content

Commit ab1a582

Browse files
committed
Fixes rails#41521, ActiveModel::Dirty fails on to_json
1 parent cde84b8 commit ab1a582

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

activemodel/CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
* Fix `to_json` for `ActiveModel::Dirty` object.
2+
3+
Exclude +mutations_from_database+ attribute from json as it lead to recursion.
4+
5+
*Anil Maurya*
6+
17
* Add `ActiveModel::AttributeSet#values_for_database`
28

39
Returns attributes with values for assignment to the database.

activemodel/lib/active_model/dirty.rb

+5
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,11 @@ def initialize_dup(other) # :nodoc:
140140
@mutations_from_database = nil
141141
end
142142

143+
def as_json(options = {}) # :nodoc:
144+
options[:except] = [options[:except], "mutations_from_database"].flatten
145+
super(options)
146+
end
147+
143148
# Clears dirty data and moves +changes+ to +previous_changes+ and
144149
# +mutations_from_database+ to +mutations_before_last_save+ respectively.
145150
def changes_applied

activemodel/test/cases/dirty_test.rb

+16
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# frozen_string_literal: true
22

33
require "cases/helper"
4+
require "active_support/json"
45

56
class DirtyTest < ActiveModel::TestCase
67
class DirtyModel
@@ -237,4 +238,19 @@ def save
237238
test "model can be dup-ed without Attributes" do
238239
assert @model.dup
239240
end
241+
242+
test "to_json should work on model" do
243+
@model.name = "Dmitry"
244+
assert_equal "{\"name\":\"Dmitry\",\"color\":null,\"size\":null,\"status\":\"initialized\"}", @model.to_json
245+
end
246+
247+
test "to_json should work on model with :except string option " do
248+
@model.name = "Dmitry"
249+
assert_equal "{\"color\":null,\"size\":null,\"status\":\"initialized\"}", @model.to_json(except: "name")
250+
end
251+
252+
test "to_json should work on model with :except array option " do
253+
@model.name = "Dmitry"
254+
assert_equal "{\"color\":null,\"size\":null,\"status\":\"initialized\"}", @model.to_json(except: ["name"])
255+
end
240256
end

0 commit comments

Comments
 (0)