【发布时间】:2014-03-25 12:20:15
【问题描述】:
是否有可能测试是否已经存在同名元素?
假设我有一个数组,如下所示:
lregion=["de", "eu", "us", "it"]
我想用这个脚本将它们放在我的表格中,然后,如果已经有一个名为“eu”的元素,则不应再次创建它。
lregion.each do |x|
if #this "actually" should test, if there is already a country with this countrycode
Country.create(countrycode: x) #creates Country
end
end
这样做很重要,因为我在我的种子文件中使用了这个脚本,不能只在我的模型中使用uniqueness: true,因为它会使seeds.rb 崩溃。
有人对我的问题有想法吗?
【问题讨论】:
-
要么验证唯一性并挽救错误,要么使用 first_or_create
标签: ruby-on-rails arrays activerecord if-statement