Rails seed data example
Contact me at LinkedIn  RailsZilla at Facebook  RailsZilla at twitter   google +1  Contact me at Xing  connect me at github

Rails seed data example

Posted in Rails

The most ugly code smells in Rails applications is the use of migrations as a way to carry seed data. This is data that needs to be added to the database on deployment. I really hate it, because it’s hard to maintain and doesn’t play well with loading up the database from the schema file.

Thank god we have the seed-functionality!
This is a file convention and also a rake task. This file is located at db/seeds.rb and it can contain arbitrary Ruby code. To give you an idea, this small example will help you:

1
2
cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
Mayor.create(:name => 'Daley', :city => cities.first)

Let’s take an Example: We have several Countries to load into our database. This could be done by simply:

1
2
3
4
Country.create({"name"=>"Deutschland", "population"=>81831000})
Country.create({"name"=>"Frankreich", "population"=>65447374})
Country.create({"name"=>"Belgien", "population"=>10839905})
Country.create({"name"=>"Niederlande", "population"=>16680000})


The other way is to execute Ruby Code. This would look something like:

1
2
3
4
5
6
7
8
9
10
country_list = [
  [ "Deutschland", 81831000 ],
  [ "Frankreich", 65447374 ],
  [ "Belgien", 10839905 ],
  [ "Niederlande", 16680000 ]
]

country_list.each do |country|
  Country.create( :name => country[0], :population => country[1] )
end

This is the same thing, just to show you that you can also code with ruby in your seeds.

When you are finished adding data to your seed.rb, you have to load the data into your database:

1
rake db:seed

If you wish to use UTF8 then you have to put this into the first line into the seeds.rb:

1
# ruby encoding: utf-8

You can also fire something like

1
rake db:setup

which runs create, schema:load, and seed in succession.
Now let’s fire data into our applications.
Happy hacking ;-)

Tags: , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please enter a secure code to see if you are a spammer ;-)

 

Copyright © 2011-2018  - RailsZilla – Ruby on Rails tutorials, tips and tricks All rights reserved. | Imprint | Privacy