Ruby/ActiveRecord not detecting changes after stripping whitespace from field

activerecord, mysql, ruby

Solution

When you do in-place modifications on model attributes, no assignment occurs and the model is unaware any changes have been made. The correct way to do this is to reassign:

foo.name = foo.name.lstrip

This triggers the `name=` method and the dirty tracking is engaged.

Problem

I am trying to remove whitespace and carriage returns from various fields in a MySQL database using the 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 I do: ``` foo.name = "John Jones" foo.save => true People.find(1).name => "John Jones" # this works and saves to database ``` I've searched all over for this... any suggestions?

Original source