#179
Sep 14, 2009

Seed Data

Rails 2.3.4 includes a conventional way to add seed data to your application - no more including it in the migration files.
Download (13.5 MB, 7:56)
alternative download for iPod & Apple TV (9.3 MB, 7:56)

Resources

script/generate model operating_system name:string
script/generate model country name:string code:string
rake db:migrate
rake db:seed
# db/seeds.rb
require 'open-uri'
require 'active_record/fixtures'

["Windows", "Linux", "Mac OS X"].each do |os|
  OperatingSystem.find_or_create_by_name(os)
end

Country.delete_all
open("http://openconcept.ca/sites/openconcept.ca/files/country_code_drupal_0.txt") do |countries|
  countries.read.each_line do |country|
    code, name = country.chomp.split("|")
    Country.create!(:name => name, :code => code)
  end
end

Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "operating_systems")

RSS Feed for Episode Comments 28 comments

1. George Yacoub Sep 14, 2009 at 00:24

Thanks Ryan.
By the way for those who use firefox you can increase the site width for this site using a style I created a while ago.
You can find it here.
http://userstyles.org/styles/15366


2. rwz Sep 14, 2009 at 00:45

great screencast as always.

btw, what plugin do you use to nicely display db-records in console as a table?


3. autologo Sep 14, 2009 at 01:04

Thank you very much!


4. Zoloo Sep 14, 2009 at 02:26

Another great one. Thank you.


5. elad Sep 14, 2009 at 02:41

@rwz he is using Hirb http://tagaholic.me/2009/03/13/hirb-irb-on-the-good-stuff.html


6. rwz Sep 14, 2009 at 04:58

@elad tnx


7. axgle Sep 14, 2009 at 07:10

O(∩_∩)O~good!


8. Jaime Iniesta Sep 14, 2009 at 08:00

Thanks, Ryan!

It's indeed a very simple addition to rails, but it provides a good convention. I used to do this initial data loading on a custom rake task, normally called something like rake project:install, which would migrate the database and load initial data, including an admin user as well.


9. Shreyans Sep 14, 2009 at 09:09

Thanks Ryan for another great episode. I think I can use it in my project. I am working on migrating legacy data from my postgres database to SQL server database with some added columns and schema changes. Can anyone tell me how can I accomplish this with some custom rake task? Can I use the concept in this episode to accomplish this. If yes, how do I read data from another database and insert it to my new database with some modification if needed?
My idea here is one this rake task is written, I can just run that rake task during deployment and get the data populated in the new database from the QA database.
I will appreciate your good suggestions.


10. mrkris Sep 14, 2009 at 09:46

What's the benefit of using the built in vs seed_fu?


11. Jeffrey Lee Sep 14, 2009 at 10:57

What are your recommendations for sequential migrations that require seed data from previous migrations?

This generally only applies to legacy databases. I might need to move users from a legacy table to a new table and relate them to yet-to-be-seeded data (such as a default group).

Is it possible to have multiple seed files? And just reference them in the migration?


12. rjordan Sep 14, 2009 at 14:04

I love the new additions to rails, both 2.3 and 3.0; however this is NOT one of my favorites. I feel this feature was thrown in without a lot of thought about its uses. If you are doing incremental design and adding new features only as you need them, then this feature is outright broken.

For example, say I have a migration that creates an "issues" table and that table has a link to a status table on it. I use seeds.rb to insert "Open", "Closed" etc into the status table. Later I decided I need to add priority to issues and I add a priority table... wait how can I seed this table, seeds.rb has already been run and I don't want to reseed my status table, I may have user values in there now.

The only way I really see this working would be to add a seeds directory next to the migrations directory and create a seed file for each migration that gets run after the migration. Otherwise we will have to keep adding any seeds past the first into the migrations.


13. Anders Sep 15, 2009 at 04:43

Good job, though I agree with rjordan about the usefulness of this particular feature. Also, perhaps it's time for captcha here? I don't know why, but it seems alot of rails blogs are cluttered with spam comments.


14. Howard Sep 15, 2009 at 14:37

On the subject of seed data, I was wondering what is the best approach for accessing records in code. At present I use, for example...

def self.Pending() find(1); end

...inside my seeded models like OrderStatus. Then I can test using order.status == OrderStatus.Pending. The problem is that these class methods are evaluated when the environment loads, which is necessary to load seed data in the first place. It would also be nice to be able to cache these objects for the life of the application, as they are only referring to static data after all. Is there a more appropriate convention for this which maintains the readability of the code I have? Thanks!


15. docgecko Sep 16, 2009 at 04:34

Perfect timing, I has just been implementing fixtures for testing using another method, but obviously this is just great.

Thanks Ryan!


16. Mark Sep 16, 2009 at 13:41

I think the countries seed should use

Country.find_or_create_by_name_and_code(name, code)

so that you don't delete the countries that are referenced by other tables (if you chose to do that)


17. loushizan Sep 20, 2009 at 20:06

nice work


18. limeyd Sep 29, 2009 at 18:09

So if you call Country.delete_all won't the break all previous associations! Unless your index is based on country code which should be noted in the migration creation.


19. Tiny Clanger Oct 01, 2009 at 06:02

OK, so with seed-fu, rake db:seed RAILS_ENV=test would seed the test database. With the builtin method, it doesn't. How do I get seed data into the test environment?

(Yes, it needs to be there — there's a validates_existence_of that depends on the seed data being loaded…)


20. Mani Oct 07, 2009 at 15:31

Great railscast as usual.

Just one suggestion. For lists of countries and states, the Carmen gem is way better than copy-and-pasting:

http://github.com/jim/carmen

You also get some handy helpers to convert between full name and abbreviation.


21. Luciano Bezerra Oct 11, 2009 at 12:48

Ryan Boa Tarde!

Estou usando o código a seguir para popular algumas tabelas:

http://pastie.org/650693

Ocorre que se executar mais de uma vez, a sequence do postgres continua. Como poderia fazer para resetar a sequence sempre que rodar rake db:seed ???

Abraços


22. Melentiy Nov 06, 2009 at 02:47

Thank you for its - much help in decision of my problems


23. Ravindra Nov 26, 2009 at 04:37

Use rake
db:seed SEED='file_matching_ pattern'
for specific file to populate the database.
Enjoy and do not again repeatedly update all the seed_fu dependent tables again and again


24. Francisco Tufró Dec 06, 2009 at 12:27

Hi ryan.
I've created a plugin to seed data acording to the environment being loaded.

I've been using it to seed testing, staging and production databases with different kinds of data without having a big seeds.rb.
Check it out!
http://github.com/franciscotufro/environmental_seeder


25. louis vuitton replica Mar 12, 2010 at 05:32

good thank you


26. topstylesbag Mar 28, 2010 at 19:51

here it is


27. jam May 04, 2010 at 03:41

Hey you have written a detailed analysis about this topic,I wonder how and where you get this information from. I would like to know more about the same . Would really appreciate if I could get more insights about this.


28. Tim McEwan Jun 15, 2010 at 00:09

Wow Ryan, that's a lot of spam you've managed to harvest. :-) Perhaps a CAPTCHA of some sort might be in order?

I hope my clicking those links for you at least puts them in a queue so you can "delete all".


29. nike shoxs Jul 01, 2010 at 19:26

I want to say very thank you for this great informations. now i understand about it. Thank you !xc


30. webtasarim Jul 15, 2010 at 09:04

web tasarımı, kurumsal site tasarımı, profesyonel web sitesi tasarımı, profesyonel web tasarımı

<a href="http://www.webtasarimturk.net" title="web tasarımı">web tasarımı</a>


31. Louis Vuitton Camera Bag M95348 Jul 16, 2010 at 20:33

great website,have very interested articles ,i have visit 'em ,to bekam more and more info!!!!!!!!!!!!!!!!!


32. iPhone Ringtone Maker for mac Jul 20, 2010 at 18:52

ah ha ,so ^^


33. mert Jul 21, 2010 at 06:05

i, interesting post. I have been pondering this topic,so thanks for writing. I'll probably be coming back to your blog...<a href="http://www.webtasarimturk.net" title="web tasarımı">web tasarımı</a>


34. webtasarim Jul 21, 2010 at 06:05

great website,have very interested articles ,i have visit 'em ,to bekam more and more info


35. http://www.google.com Jul 21, 2010 at 06:06

eat website,have very interested articles ,i have visit 'em


36. free directory list Aug 11, 2010 at 22:37

I really appreciate what you post.


37. chapslawgeek Aug 17, 2010 at 21:23

What would the code look like to read the codes.csv file in db/seedData directory? It has three columns. name, date, location

Thank you!!


38. Swann Aug 18, 2010 at 10:58

I was virtuous browsing for relevant blog posts for my cast investigate and I happened to falter upon yours. Thanks for the functional accumulation!


39. Air Jordan Retro Aug 19, 2010 at 00:05

I really appreciate what you post. Thank you for its - much help in decision of my problems


40. Wholesale hats Aug 20, 2010 at 20:24

The blog article very surprised to me! Your writing is good. In this I learned a lot! Thank you!


41. medyum Aug 22, 2010 at 02:54

The information you provided was very useful. Because of your help, thank you


42. vibram fivefingers Aug 23, 2010 at 22:05

Manchester City celebrated owner Sheikh Mansour's first visit to Eastlands by delivering an impressive performance to cruise to victory against Liverpool.
Sheikh Mansour has changed the face of Manchester City since his takeover two years ago - and this latest expensively reconstructed version of Roberto Mancini's squad provided evidence that they may be able to meet the expectations that will accompany his huge financial outlay.


43. buy jordans Aug 24, 2010 at 23:04

The info is useful.thanks great. I like your information so much. It is something worth appreciating by us. It is very kind thing to see your wonderful post! I perfectly agree with you! That should always be the case.


44. Wholesale Electronics Aug 25, 2010 at 01:38

Discount Wholesale Electronics, Wholesale Cell Phones, Electronic Gadgets and More from the Best Dropship Wholesaler


45. louis vuitton shoes Aug 26, 2010 at 21:18

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


46. snow boots Aug 30, 2010 at 20:48

Manchester City since his takeover two years ago - and this latest expensively reconstructed version of Roberto Mancini's squad provided evidence that they may be able to meet the expectations that will accompany his huge financial outlay.


47. air jordans 13 Sep 01, 2010 at 00:03

air jordans 13


48. levis belts Sep 01, 2010 at 21:02

Good article! Thank you so much for sharing this post.Your views truly open my mind.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source