[英]Insert ignore into table statement in rails active records
How can i use an active record
method in rails to ignore the errors while inserting a duplicate entry. 在插入重复项时,如何在Rails中使用active record
方法来忽略错误。 My database already has unique specified in it. 我的数据库已经在其中指定了唯一性。
With Rails >= 3, you can use this: 在Rails> = 3的情况下,您可以使用以下命令:
begin
Device.create!(attributes)
rescue ActiveRecord::RecordNotUnique
# The device already exists.
end
It's important that you use the create! 使用create很重要! (with trailing bang char). (带有结尾的bang char)。 This raises an exception if the record can't be saved for whatever reason, in this case we are aiming to rescue ActiveRecord::RecordNotUnique
. 如果由于某种原因无法保存记录,则会引发异常,在这种情况下,我们的目标是抢救ActiveRecord::RecordNotUnique
。
I recommend you to put this on a model method with a descriptive name, like create_if_not_exists
. 我建议您将其放在具有描述性名称的模型方法上,例如create_if_not_exists
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.