Dylan
Dylan

Reputation: 55

update_attributes returns true but the string hasn't changed

When using update_attributes in the following way:

title = Post.first.title
title.gsub!(/a/, 'b')
Post.first.update_attributes(:title => title)

I find that the title is not properly saved back to the database, and when I reload it, the 'a' has not been changed into 'b'.

Upvotes: 0

Views: 722

Answers (1)

Dylan
Dylan

Reputation: 55

ActiveRecord judges whether an attribute has changed by looking whether the object ID of the attribute value has changed. You passed back the same object, and that is regarded as nothing being changed.

Changing the code to the following will fix the problem:

title = Post.first.title
title = title.gsub(/a/, 'b')
Post.first.update_attributes(:title => title)

Returning a different string lets the change be detected by ActiveRecord and be saved to the database.

Upvotes: 2

Related Questions