I'm using Rails 3.0.3 and have data for my "categories" table already in the database, but want to create a seed file from it. Is there any rake task that will generate the seeds.rb format for me from this table?
4 Answers
There is a gem called seed_dump
, which will do exactly what you want:

- 48,006
- 27
- 136
- 235

- 836
- 8
- 5
-
10I found the new Github home in case anyone is looking for it - https://github.com/zenprogrammer/seed_dump – rcd Feb 09 '13 at 19:14
-
1The RubyGems page links to https://github.com/rroblak/seed_dump currently (Feb. 8th, 2014). EDIT: I guess the above zenprogrammer link now redirects to the new one as well. – streetlogics Feb 08 '14 at 22:22
-
1Works great!! `rake db:seed:dump` and your off and running --thanks. – Jordan Jul 18 '14 at 05:57
-
5this is not working with associations can we also include id of the record? – Asnad Atta Jan 29 '15 at 08:19
-
Very easy to use. However, it fails to preserve the serial ids on records - in other words the IDs you see in the origin DB may not end up being the same once rails db:seed has run on the destination database. It also doesn't sequence the create! blocks such that dependent records are created first. This means that you probably need to manually resequence your create! blocks so that rails db:seed doesn't choke on missing foreign keys: https://github.com/rroblak/seed_dump/issues/83. – MSC Sep 26 '18 at 23:18
Not sure about any existing rake tasks, but you can try running something like this in the rails console & paste the results into your seeds.rb file
(warning: dirty & untested)
c = Category.all
c.each do |cat|
puts "Category.create(:name => '#{cat.name}')"
end
Adjust for any additional fields you may have.
Hope this helps.

- 6,820
- 3
- 29
- 27
Old question, I have a new one based on @Brian's answer.
If you want to keep the entire row as is:
seedfile = File.open('db/seeds.rb', 'a')
c = Category.all
c.each do |cat|
seedfile.write "Category.create(#{cat.attributes})\n"
end
seedfile.close
If you want to only write some attributes, change the write line to the following:
seedfile.write "Category.create(#{cat.attributes.slice('attr1', 'attr2', ...})\n"
Or, if you wish all the attributes except some, for example timestamps:
seedfile.write "Category.create(#{cat.attributes.except('created_at', 'updated_at')})\n"

- 5,690
- 1
- 26
- 43
I've used YamlDb to dump data from my development db and then load it up to another server. It dumps the data to a Yaml file, which will be used any time you want to use db:load to push it up to any other db server.

- 9,115
- 5
- 43
- 52