简体   繁体   English

rails validates_uniqueness_of无法正常工作

[英]rails validates_uniqueness_of not working as it should

I have an account model like so 我有一个这样的帐户模型

class Account < ActiveRecord::Base
end

I had some duplicates records on it in production so I've added this line to it 我在生产中有一些重复的记录,所以我在这行中添加了

validates_uniqueness_of :owner_id, :on => :create

so it will only verify this on new records and NOT on save! 因此它将仅在新记录上对此进行验证, 而不save!

it works on localhost and even on console on production. 它可以在localhost上运行,甚至可以在生产环境的控制台上运行。 but I have a job that runs every 10 minutes that uses rails runner and it fails for 但我有一份工作每10分钟运行一次,使用的是railsRunner,但失败了

Validation failed: Owner has already been taken (ActiveRecord::RecordInvalid)

The runner does some actions on accounts and then saves them. 赛跑者对帐户执行一些操作,然后保存它们。

am I doing something wrong on this syntax ? 我在这种语法上做错了什么吗?

Only time I've seen this happen was when a controller "create" action was being sent as a :get request (instead of :post as it should be in REST). 我只有在看到这种情况发生时,才以:get请求(而不是在REST中使用:post)发送控制器“创建”动作。 The result was the validation didn't realize it was doing a :create. 结果是验证没有意识到它正在执行:create。 Doesn't sound like what you've got here... but maybe similar? 听起来不像您在这里...但是可能类似吗? FYI my fix at the time was to use if: :new_record? 仅供参考,当时我的解决方法是使用if: :new_record? instead of on: :create until the request type could be fixed. 而不是on: :create直到请求类型可以固定。 You could try this. 你可以试试看。

Also, you can put a debug statement into the validation to interrogate the state of the object during that validation with eg if: -> { binding.pry } or if: -> { debugger } (depending on what you use to debug with, of course). 另外,您可以在验证中加入调试语句,以在验证期间询问对象的状态,例如if: -> { binding.pry }if: -> { debugger } (取决于您用于调试的对象,当然)。 Hopefully that will help figure out what the runner is doing different. 希望这将有助于弄清楚跑步者在做什么。 You can ask the object if it's a new_record? 您可以询问对象是否为new_record? or what changes it has to save, etc. 或它必须保存什么changes等。

我发现此方法没有:on =>:仅创建:if,所以我这样做了:

validates_uniqueness_of :owner_id, :if =>  Proc.new { |account| account.created_at > Time.now - 10.seconds }

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

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