【问题标题】:Ruby/ActiveRecord not detecting changes after stripping whitespace from field从字段中删除空格后,Ruby/ActiveRecord 未检测到更改
【发布时间】:2012-10-12 20:09:43
【问题描述】:

我正在尝试使用 mysql2 适配器和 ActiveRecord 从 MySQL 数据库中的各个字段中删除空格和回车:
红宝石 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.

如果我这样做:

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

我已经到处搜索了...有什么建议吗?

【问题讨论】:

    标签: mysql ruby activerecord


    【解决方案1】:

    当您对模型属性进行就地修改时,不会发生分配,模型也不知道已进行任何更改。正确的做法是重新分配:

    foo.name = foo.name.lstrip
    

    这会触发name= 方法并进行脏跟踪。

    【讨论】:

    • 很高兴听到。您可以使用复选标记突出显示有效答案并将其作为解决方案接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2013-07-14
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多