【问题标题】:Using find_or_create_by to seed a database使用 find_or_create_by 为数据库播种
【发布时间】:2015-06-29 11:15:52
【问题描述】:

我目前正在我的应用程序中创建种子文件,并希望确保没有使用此post 中建议的find_or_create_by 创建重复项。我正在使用find_or_create_by_name,但出现此错误:

NoMethodError: undefined method `find_or_create_by_name' for #<Class:0x007fa9680cb688>

这是我在种子文件中使用的

Genre.find_or_create_by_name([
    {name: "Alternative"}, 
    {name: "Country"}, 
    {name: "Electronic"}
    ])

也值得一问。如果我有一个模型名称的唯一性验证器,find_or_create_by 仍然是必要的吗?

【问题讨论】:

    标签: ruby-on-rails database activerecord model


    【解决方案1】:

    新版本的 Rails 使用稍微不同的语法:

    Genre.find_or_create_by(name: 'Alternative')
    

    find_or_create_by 不支持一次添加多条记录,因此您必须构造一个哈希数组并多次调用find_or_create_by

    hashes = [
      {name: "Alternative"}, 
      {name: "Country"}, 
      {name: "Electronic"}
    ]
    
    hashes.each do |hash|
      Genre.find_or_create_by(hash)
    end
    

    【讨论】:

      【解决方案2】:

      或者,您可以使用以下内容:

      User.where(name: "Alice").first_or_create
      

      这将返回名为“Alice”的第一个用户,或者如果没有用户,它将创建并返回一个名为“Alice”的新用户。

      这并不意味着您不能拥有多个名为“Alice”的用户,因为如果他们之前在数据库中,您只会找到第一个。

      【讨论】:

        猜你喜欢
        • 2014-03-01
        • 1970-01-01
        • 2011-08-29
        • 2015-09-25
        • 1970-01-01
        • 2011-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多