Skip to content

Commit

Permalink
Return true if attribute is not changed for update_attribute
Browse files Browse the repository at this point in the history
- If the attribute is not changed, then update_attribute does not run
  SQL query, this effectively means that no change was made to the
  attribute.
- This change was made in rails/rails@0fcd4cf
  to avoid a SQL call.
- But the change resulted into `nil` being returned when there was no
  change in the attribute value.
- This commit corrects the behavior to return true if there is no change
  in attribute value. This is same as previous behavior of Rails 4.2
  plus benefit of no additional SQL call.
- Fixes rails#26593.
  • Loading branch information
prathamesh-sonpatki committed Sep 25, 2016
1 parent fbb8d53 commit 75f274c
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
7 changes: 7 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,10 @@
* Return `true` from `update_attribute` when the value of the attribute
to be updated is unchanged.

Fixes #26593.

*Prathamesh Sonpatki*

* Serialize JSON attribute value `nil` as SQL `NULL`, not JSON `null`

*Trung Duc Tran*
Expand Down
3 changes: 2 additions & 1 deletion activerecord/lib/active_record/persistence.rb
Expand Up @@ -252,7 +252,8 @@ def update_attribute(name, value)
name = name.to_s
verify_readonly_attribute(name)
public_send("#{name}=", value)
save(validate: false) if changed?

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

# Updates the attributes of the model from the passed-in hash and saves the
Expand Down
8 changes: 4 additions & 4 deletions activerecord/test/cases/persistence_test.rb
Expand Up @@ -391,14 +391,14 @@ def self.name; 'Topic'; end
end
topic = klass.create(title: 'Another New Topic')
assert_queries(0) do
topic.update_attribute(:title, 'Another New Topic')
assert topic.update_attribute(:title, "Another New Topic")
end
end

def test_update_does_not_run_sql_if_record_has_not_changed
topic = Topic.create(title: 'Another New Topic')
assert_queries(0) { topic.update(title: 'Another New Topic') }
assert_queries(0) { topic.update_attributes(title: 'Another New Topic') }
topic = Topic.create(title: "Another New Topic")
assert_queries(0) { assert topic.update(title: "Another New Topic") }
assert_queries(0) { assert topic.update_attributes(title: "Another New Topic") }
end

def test_delete
Expand Down

0 comments on commit 75f274c

Please sign in to comment.