Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Using shovel operator to update a string attribute on a model does not make the model dirty

We ran into an interesting problem today. It seems that if you use the shovel operator to concatenate a string attribute on an ActiveRecord model, it doesn't make the model dirty. For example:

e = Employee.first
e.name << "asdf"
e.name_changed? # returns false
e.changed? # returns false

This makes sense since the shovel operator updates a string without making a copy of it, where the += operator will make a copy of the string. I don't see how ActiveRecord could possibly know that something changed if you use the shovel operator.

Has anyone else seen this? Is the solution to just use += instead of << when concatenating strings?

like image 226
Jon Kruger Avatar asked Nov 09 '10 20:11

Jon Kruger


1 Answers

The solution is was you write.

Or you can mark before that your attibute will_change

e = Employee.first
e.name_will_change!
e.name << "asdf"
e.name_changed? # => true

It's mark on the API documentation. ActiveModel::Dirty

like image 100
shingara Avatar answered Sep 28 '22 05:09

shingara