Posted By

markpercival on 04/23/08


Tagged

rails activerecord


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

webstic
cforcey


YAML ActiveRecord Dump


 / Published in: Ruby
 

I didn't create this but I use it all the time. Just drop it in lib/tasks/fixtures.rake

  1. namespace :db do
  2. namespace :fixtures do
  3.  
  4. desc 'Create YAML test fixtures from data in an existing database.
  5. Defaults to development database. Set RAILS_ENV to override.'
  6. task :dump => :environment do
  7. sql = "SELECT * FROM %s"
  8. skip_tables = ["schema_info"]
  9. ActiveRecord::Base.establish_connection(RAILS_ENV)
  10. (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
  11. i = "000"
  12. File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
  13. data = ActiveRecord::Base.connection.select_all(sql % table_name)
  14. file.write data.inject({}) { |hash, record|
  15. hash["#{table_name}_#{i.succ!}"] = record
  16. hash
  17. }.to_yaml
  18. end
  19. end
  20. end
  21. end
  22. end

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: cforcey on July 14, 2010

For Rails 3, change:

RAILSENV to Rails.env.tos #This variable is now a "StringInquirer" and will throw an error when you try to "symbolizekeys" on it. RAILSROOT to Rails.root #Just to get in the Rails 3 style

Cheers! Thanks for the snippet. The AR_FIXTURES gem does similar things by extending active record, but this is less invasive (by far) and great for those of us who just need translations or some other handy data dumped into a fixture.

You need to login to post a comment.