Dylan Richards
Dylan Richards

Reputation: 708

Mass create instances of models?

In front of me on a sheet of paper, I have a list of 107 Names, Hometowns, Dates of Birth, and Genders.

In my Rails application, I ran

rails g scaffold Person name hometown dob gender.

Do I have to manually add each Person to the database through the form that was created? Is there a way to do this from my text editor instead?

Upvotes: 0

Views: 78

Answers (1)

KappaNossi
KappaNossi

Reputation: 2716

You can use the seed.rb file in your db folder. You can execute arbitrary Ruby statements to create your objects and save (or update) them to your database. Simply list a bunch of statements like this one and execute the db:seed Rake task.

Person.create(:name => 'Bob', :hometown => 'Bobington', :dob => '1980-06-25', :gender => 'male')

Note that the task will fail if one of the created records fails a unique check or something similar (i.e. cannot be inserted into the db). Use other rake tasks (db:drop, db:create, db:migrate) to 'clean' the db if you can or empty the tables by hand if you cannot wipe it.

Upvotes: 3

Related Questions