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

Always reset changed attributes in becomes

When ```becomes``` changes @attributes it should also change
@changed_attributes. Otherwise we'll experience a kind of split head situation
where attributes are coming from ```self```, but changed_attributes is coming
from ```klass.new```. This affects the inheritance_colmn as it's changed by new
for example.

Fixes #16881
This commit is contained in:
Miklos Fazekas 2014-10-02 10:02:30 +02:00
parent 1405c7a2cb
commit 5f6370a81b
3 changed files with 14 additions and 1 deletions

View file

@ -1,3 +1,9 @@
* Fixed ActiveRecord::Relation#becomes! and changed_attributes issues for type column
Fixes #17139.
*Miklos Fazekas*
* Fixed several edge cases which could result in a counter cache updating
twice or not updating at all for `has_many` and `has_many :through`.

View file

@ -208,7 +208,8 @@ module ActiveRecord
def becomes(klass)
became = klass.new
became.instance_variable_set("@attributes", @attributes)
became.instance_variable_set("@changed_attributes", @changed_attributes) if defined?(@changed_attributes)
changed_attributes = @changed_attributes if defined?(@changed_attributes)
became.instance_variable_set("@changed_attributes", changed_attributes || {})
became.instance_variable_set("@new_record", new_record?)
became.instance_variable_set("@destroyed", destroyed?)
became.instance_variable_set("@errors", errors)

View file

@ -121,6 +121,12 @@ class InheritanceTest < ActiveRecord::TestCase
assert_kind_of Cabbage, cabbage
end
def test_becomes_and_change_tracking_for_inheritance_columns
cucumber = Vegetable.find(1)
cabbage = cucumber.becomes!(Cabbage)
assert_equal ['Cucumber', 'Cabbage'], cabbage.custom_type_change
end
def test_alt_becomes_bang_resets_inheritance_type_column
vegetable = Vegetable.create!(name: "Red Pepper")
assert_nil vegetable.custom_type