【问题标题】:test if name is already used测试名称是否已被使用
【发布时间】: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


【解决方案1】:

你会使用find_or_create:

<% lregion.each do |x| %>
   <% Country.find_or_create_by(countrycode: x.country_code) %>
<% end %>

这将搜索country_code是否已经注册,如果没有,则会创建一个新的。

【讨论】:

  • 非常有帮助!谢谢!但我意识到,它完全适用于验证唯一性。但是你的很有帮助!我需要它来自动创建多对多关系。谢谢!
  • 很高兴它有帮助:) 我认为它可以与验证唯一性一起使用,但你提到它会搞砸其他事情。 :)
【解决方案2】:

我之前的声明

这样做很重要,因为我在我的种子文件中使用了这个脚本,并且不能只在我的模型中使用 uniqueness: true ,因为它会使 seed.rb 崩溃。

错了。我可以轻松使用它!

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 2017-02-12
    • 1970-01-01
    • 2021-03-28
    • 2015-10-20
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多