I just started building a new Rails application in version 2.3.4. One feature that I thought was particularly handy is the data seeding that is now built into Ruby on Rails.
Before this feature, you would have to do one of two things. You could seed your data in your migrations. The problem with this approach is that it clutters up your migrations, and can make for more brittle migrations. It also may or may not propagate to your test database when you run your tests, meaning that if you’re counting on it, it may not bee there.
Your second option was to create fixtures and a rake task to import the fixture data into your Rails application. The problem with this is the need to create multiple related objects across multiple files to make all of your data match up, which can create maintenance problems.
So, without further ado, here is the solution now included in Rails. You simple create a file at db/seeds.rb and place ActiveRecord create calls in the file. Here’s an example seeds.rb.
Role.create(:name => "admin") User.create(:name => "Chuck Wood", :username => "chuck", :password => "chuck") Post.create(:title => "Welcome to the blog", :content => "Welcome to my blog! I hope you enjoy it!", :author => User.find_by_name("Chuck Wood"))
Once you have this file, all you need to do is run rake db:setup to create the database and seed the data or rake db:seed to seed the data into an existing database.