Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/ActiveRecord not detecting changes after stripping whitespace from field

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?

like image 210
Jason Avatar asked Oct 12 '12 20:10

Jason


1 Answers

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.

like image 68
tadman Avatar answered Oct 20 '22 20:10

tadman