Ruby/ActiveRecord在从字段中删除空格后没有检测到更改

Jas*_*son 7 ruby mysql activerecord

我试图使用mysql2适配器和ActiveRecord从MySQL数据库中的各个字段中删除空格和回车:
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.
Run Code Online (Sandbox Code Playgroud)

如果我做:

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

我已经搜遍了这个......有什么建议吗?

tad*_*man 7

当您对模型属性进行就地修改时,不会发生任何分配,并且模型不会发现任何已进行的更改.正确的方法是重新分配:

foo.name = foo.name.lstrip
Run Code Online (Sandbox Code Playgroud)

这会触发该name=方法并启用脏跟踪.