简体   繁体   English

rails更新时的唯一性验证

[英]rails validation of uniqueness on update

I have the following validation rule on one of the models, 我在其中一个模型上有以下验证规则,

validates :reciept_num, :presence => true,
                        :numericality => { :only_integer => true },
                        :uniqueness => true,
                        :on => :update,
                        :if => "!status_id.nil?"`

Now, when I update the object using update_attributes method it gives me following error 现在,当我使用update_attributes方法更新对象时,它会给我以下错误

reciept_num: has already been taken . reciept_num: has already been taken

While updating the the object I'm not changing the reciept_num attribute? 在更新对象时,我没有更改reciept_num属性? So, why does this validation fails on update? 那么,为什么这个验证在更新时失败了?

If I'm not updating the value, it must be the old one and hence should pass validation. 如果我没有更新值,它必须是旧的,因此应该通过验证。 Am I missing something. 我错过了什么。

First off, validations don't run based on whether the attribute has changed or not (unless of course you ask for that explicitly). 首先,验证不会根据属性是否已更改而运行(当然,除非您明确要求验证)。 Everytime a record with a uniqueness validation saves and the validation can run (as defined by :on , :if , :unless options) it will check whether there are any instances other than itself with the value that is supposed to be unique. 每次具有唯一性验证的记录都会保存并且验证可以运行(由:on:if :unless选项),它将检查是否存在除自身以外的任何实例,其值应该是唯一的。

Since you've got conditions on your validation, I imagine you could end up creating two instances with the same receipt num, but where both have a null status_id . 由于您的验证有条件,我想您最终可能会创建两个具有相同收据num的实例,但两者都具有null status_id Set the status_id column and the validation kicks into action and finds the other instances. 设置status_id列并将验证踢入操作并查找其他实例。

Another thing is that since your validation is on update only you could create multiple instances with the same receipt num, again trying to update the record would trigger the validation. 另一件事是,由于您的验证只在更新时,您可以创建具有相同收据num的多个实例,再次尝试更新记录将触发验证。

I'm only guessing at the precise scenarios though. 我只是猜测精确的场景。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM