Ruby / ActiveRecord does not detect changes after removing spaces from a field

I am trying to remove spaces and carriage returns from different fields in a MySQL database using mysql2 adapter and ActiveRecord:
Ruby 1.9.3p194
ActiveRecord 3.2.8
MySQL 5.5.28

foo = People.find(1) foo.name => "\rJohn Jones" foo.name.lstrip! => "John Jones" foo.name => "John Jones" foo.changes => {} #no changes detected to foo.name??? foo.save => true # but does nothing to database. 

if a:

 foo.name = "John Jones" foo.save => true People.find(1).name => "John Jones" # this works and saves to database 

I searched everything for this ... any suggestions?

+7
source share
1 answer

When you perform in-place modifications in the attributes of a model, no assignment occurs and the model does not know what changes have been made. The correct way to do this is to reassign:

 foo.name = foo.name.lstrip 

This calls the name= method, and dirty tracking is enabled.

+7
source

All Articles