Search code examples
ruby-on-railsrubyrake

How to create seeds.rb array?


I'd like to populate the Department table using the seeds.rb file. I've created only two columns in the table. There are three more created by rails (id, created_at, updated_at).

When I run rake db:seed, I get the following error:

ArgumentError: wrong number of arguments (3 for 0..1)

Here's what the seeds.rb file looks like:

departments = Department.create([{ depttitle: 'dept 1' }, { deptdescription: 'this is the first dept' }],
[{ depttitle: 'dept 2' }, { deptdescription: 'this is the second dept' }],
[{ depttitle: 'dept 3' }, { deptdescription: 'this is the third dept' }])

Is the issue with how I've created the array or something else?


Solution

  • The reason it didn't work is that you actually passed three arrays with two hashes in each of them.

    Pass a single array to the #create method with a single hash for each record you want to create. For example:

    Department.create([{ deptitle: 'dept 1', deptdescription: 'this is the first dept' },
                       { depttitle: 'dept 2', deptdescription: 'this is the second dept' }])
    

    But instead of 'creating an array' you could use a simple loop to create Department records.

    10.times do |x|
      Department.create({deptitle: "dept #{x}", deptdescription: "this is the #{x} department"})
    end
    

    In my opinion it looks cleaner, takes less place and it is easier to change number of seed records if you need to.

    To create a numeral from a number (for "this is the Xst dept" sentence) you could use a humanize gem.