Skip to content

Commit

Permalink
Merge pull request #32871 from tarebyte/backport-update_attribute
Browse files Browse the repository at this point in the history
Backport "save attributes changed by callbacks after update_attribute"
  • Loading branch information
tenderlove committed May 11, 2018
2 parents e53f45c + 08bd4bc commit b21aa9b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/persistence.rb
Expand Up @@ -261,7 +261,7 @@ def update_attribute(name, value)
verify_readonly_attribute(name)
public_send("#{name}=", value)

changed? ? save(validate: false) : true
save(validate: false)
end

# Updates the attributes of the model from the passed-in hash and saves the
Expand Down
3 changes: 3 additions & 0 deletions activerecord/test/cases/persistence_test.rb
Expand Up @@ -493,6 +493,9 @@ def test_update_attribute

Topic.find(1).update_attribute(:approved, false)
assert !Topic.find(1).approved?

Topic.find(1).update_attribute(:change_approved_before_save, true)
assert Topic.find(1).approved?
end

def test_update_attribute_for_readonly_attribute
Expand Down
7 changes: 7 additions & 0 deletions activerecord/test/models/topic.rb
Expand Up @@ -63,6 +63,9 @@ def topic_id

after_initialize :set_email_address

attr_accessor :change_approved_before_save
before_save :change_approved_callback

class_attribute :after_initialize_called
after_initialize do
self.class.after_initialize_called = true
Expand Down Expand Up @@ -94,6 +97,10 @@ def before_save_for_transaction; end
def before_destroy_for_transaction; end
def after_save_for_transaction; end
def after_create_for_transaction; end

def change_approved_callback
self.approved = change_approved_before_save unless change_approved_before_save.nil?
end
end

class ImportantTopic < Topic
Expand Down

0 comments on commit b21aa9b

Please sign in to comment.