【问题标题】:Rake seed without validations failing没有验证失败的耙子
【发布时间】:2016-08-09 17:23:55
【问题描述】:

我正在尝试使用 rake db:seed 使用种子数据填充我的数据库,但由于某种原因,我不断收到此错误。请注意,我需要绕过验证检查。

01_user.rb
user = User.new([
  {id: 6, email: "admin@example.com"},
  {id: 7, email: "superadmin@example.com"}
])

user.save!(validate: false)

我不断收到的错误:

$ bundle exec rake db:seed RAILS_ENV=test
rake aborted!
ArgumentError: When assigning attributes, you must pass a hash as an argument.

关于为什么会发生这种情况以及如何解决它的任何指导?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rake


    【解决方案1】:

    您将散列数组传递给User 模型的new 方法。您需要对这些哈希中的每一个进行循环:

    [
      {id: 6, email: "admin@example.com"},
      {id: 7, email: "superadmin@example.com"}
    ].each do |user_attributes|
      user = User.new(user_attributes)
      user.save!(validate: false)
    end
    

    我不认为你可以覆盖 id 属性。

    【讨论】:

      【解决方案2】:

      你也可以试试这个:

      email_list = ["admin@example.com", "superadmin@example.com"]
      
      email_list.each do |email_address|
        User.create( email: email_address )
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-09
        • 2018-02-24
        • 1970-01-01
        • 2012-06-19
        • 1970-01-01
        • 1970-01-01
        • 2015-01-16
        • 2011-04-21
        相关资源
        最近更新 更多