更新期间持久性记录的唯一性验证失败

时间:2018-03-28 02:30:36

标签: ruby-on-rails

我有以下验证:

validates_uniqueness_of :case_number, scope: [:county, :case_type], allow_blank: true

在索引操作期间,我选择符合条件的记录。但我也想更新我的具体日期字段。所以我遍历所选的记录:

MyRecord.where(condition).all.collect do |my_record| 
        my_record.last_exported_date = Date.today
        new_record = my_record.new_record? # false
        valid = my_record.valid? # false
        errors = my_record.errors.full_messages # ["Case Number has already been taken"]
        my_record.save!
end  

当我调用new_record?时,它表示错误。这意味着它是现有记录。那么为什么现在的记录中“已经采用了案例编号”的验证失败呢?

1 个答案:

答案 0 :(得分:0)

因此,当您更改现有记录的属性时,它也会在更新期间运行验证(保存!如果记录保持不变)。因此,如果要在更新期间更改属性,则必须指定要验证的操作:

MATCH