Jeremy Kemper | 7 Nov 01:31
Gravatar

Re: extract fixtures from database?


On Nov 6, 2005, at 7:39 AM, Raphael Bauduin wrote:
> Hi,
> I wondered if there was a way to generate fixtures from an existing  
> database.
> Thanks
> raph

Sure, raph:

$ cat > lib/tasks/dump_fixtures.rake
desc 'Dump a database to yaml fixtures.  Set environment variables DB  
and DEST to specify the target database and destination path for the  
fixtures.  DB defaults to development and DEST defaults to RAILS_ROOT/ 
test/fixtures.'
task :dump_fixtures => :environment do
   path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures"
   db   = ENV['DB']   || 'development'
   sql  = 'SELECT * FROM %s'

   ActiveRecord::Base.establish_connection(db)
   ActiveRecord::Base.connection.table_names.each do |table_name|
     i = '000'
     File.open("#{path}/#{table_name}.yml", 'wb') do |file|
       file.write ActiveRecord::Base.connection.select_all(sql %
table_name).inject({}) { |hash, record|
         hash["#{table_name}_#{i.succ!}"] = record
         hash
       }.to_yaml
     end
   end
end

# dump dev db to test/fixtures
$ rake dump_fixtures

# dump foobar db to ./foobar
$ rake dump_fixtures DB=foobar DEST=./foobar

jeremy

Gmane