我有这个示例代码,它提出了“重复预期”。相反,如果存在重复,我只想跳过。
(1..10).each do |page|
group.products << [{id: 1, title: "Example A"}, {id: 2, title: "Example B"}]
group.save
end
产品数组只是针对此示例的静态,重要的是它具有ID,因此产品存在于数据库中。
问题是当我分配过去已经分配的产品时,会产生“非唯一异常”。在这种情况下,我会跳过该关联。怎么可能?
你可以将create_with
与find_or_create_by
结合使用:
(1..10).each do |page|
group.products << Product.create_with(title: "Example A").find_or_create_by(id: 1)
group.products << Product.create_with(title: "Example B").find_or_create_by(id: 2)
group.save
end
您将在10次循环中为group.products
分配相同的动态对象数组,从而创建重复项。你为什么不在没有循环的情况下运行它?我认为不需要循环。