Seeding Stuff

Creating a new app is really fun. Whats not so fun is having to populate the database with dummy data so you can test how things work. Even more not fun is when changes happen (yes its true, requirements sometimes change, I’ve actually seen it with my own eyes) and you have to drop the database and repopulate it again.

Thankfully, Rails has the db:seed rake task. All you have to do is modify the seed.rb file in the db folder.

There are plenty of ways to do this:
(1) Using code

      { :meal => 'Lunch', :price => 450.00},
      { :meal => 'Dinner', :price => 450.00}
     ].each do |c|
      Price.create!(:meal => c[:meal], :price => c[:price])

This takes a hash and creates two Price objects. I think arrays would work just as well.

(2) Using CSV

require 'csv'
CSV.foreach("config/languages.csv", { encoding: "UTF-8", headers: true,header_converters: :symbol, converters: :all}) do |row|

This takes a CSV file, in this case stored in the config folder.

headers: true makes the first row of the CSV file (in this case “name”) as the header. What this means can be shown below:

 CSV.foreach("config/languages.csv", { headers: true }) do |row| print row.to_hash end

Wil produce

  {"name"=>"English"}{"name"=>"Danish"}{"name"=>"Mandarin Chinese"}

header_converters: :symbol as its name suggests, makes the header into a symbol, I guess the default is a string

(3) Using text files

open("config/nationalities.txt") do |states|
  states.read.each_line do |national|
  name = national.chomp
  Nationality.create!(:name => name)

Here we use a text file, with all the nationalities having their very own line.
So you might wonder, why is there a double block in here? The answer is when we open config/nationalities.txt it returns a File object.(In this case, called “states”)
So we have to create another block that reads each line of the file individually. Then we can safely create Nationality objects with each line.

There should be more ways to do it. These are just the ones I’ve found.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s