Search code examples
ruby-on-railsrubyruby-on-rails-4activerecordrake

Rake seed without validations failing


I'm trying to populate my database with seed data using rake db:seed but for some reason I keep getting this error. Note, I need to bypass validations checks.

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

user.save!(validate: false)

Error that I keep getting:

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

Any guidance on why this is happening and how to fix it?


Solution

  • You are passing an array of hashes to the new method of User model. You need to loop on each of these hashes instead:

    [
      {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
    

    I don't think you can overwrite the id attribute though.