swrobel
swrobel

Reputation: 4230

Create seed file from data already in the database

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?

Upvotes: 58

Views: 34389

Answers (4)

John Peterson
John Peterson

Reputation: 846

There is a gem called seed_dump, which will do exactly what you want:

Upvotes: 71

Ruby Racer
Ruby Racer

Reputation: 5740

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"

Upvotes: 12

MattSlay
MattSlay

Reputation: 9975

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.

https://github.com/ludicast/yaml_db

Upvotes: 8

Brian
Brian

Reputation: 6840

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.

Upvotes: 31

Related Questions