Ruby on rails 如何一次创建多个对象并忽略唯一约束异常
有一个用于创建Ruby on rails 如何一次创建多个对象并忽略唯一约束异常,ruby-on-rails,Ruby On Rails,有一个用于创建ApplicationRecord对象的哈希数组 a = [{name: 'foo', title: 'bar'}, {name: 'foo2', title: 'bar2'}] 我可以通过Foo.create(a)创建多个对象,我可以使用rescue子句捕获唯一约束异常 但是我不知道如何一次创建多个对象,忽略了异常 我只能用循环来写 a.each do |hash| begin Foo.create(hash) rescue next en
ApplicationRecord
对象的哈希数组
a = [{name: 'foo', title: 'bar'},
{name: 'foo2', title: 'bar2'}]
我可以通过Foo.create(a)
创建多个对象,我可以使用rescue
子句捕获唯一约束异常
但是我不知道如何一次创建多个对象,忽略了异常
我只能用循环来写
a.each do |hash|
begin
Foo.create(hash)
rescue
next
end
end
或
在这种情况下,如何一次创建对象?试试这个
begin
ActiveRecord::Base.transaction do
a.each{|hash| Foo.create(hash) }
end
#handle success here
rescue ActiveRecord::RecordInvalid => exception
#handle failure here
end
例外情况如下所示
#<ActiveRecord::RecordInvalid: Validation failed: Title can't be blank>
希望这能有所帮助。:) 有什么问题吗:
# not Foo.create!(a)
Foo.create(a)
,它可以将哈希数组作为参数,保存通过验证的哈希,忽略未通过验证的哈希
顺便说一下,我不认为
Foo.create(hash)
将引发任何验证异常,因为它不是“!”版本(比如:Foo.create!(hash))。如果唯一约束异常来自数据库,而不是验证,则需要对此进行验证
# not Foo.create!(a)
Foo.create(a)
Foo.create(hash)