I have some data in my development database that I would like to utilize as fixtures in my test environment. What is the best way in Rails 2.x to export a database table to
Here's a rake task that will do exactly that (tested in Rails 3.2.8):
namespace :db do
task :extract_fixtures => :environment do
sql = 'SELECT * FROM "%s"'
skip_tables = ["schema_migrations"]
ActiveRecord::Base.establish_connection
if (not ENV['TABLES'])
tables = ActiveRecord::Base.connection.tables - skip_tables
else
tables = ENV['TABLES'].split(/, */)
end
if (not ENV['OUTPUT_DIR'])
output_dir="#{Rails.root}/test/fixtures"
else
output_dir = ENV['OUTPUT_DIR'].sub(/\/$/, '')
end
(tables).each do |table_name|
i = "000"
File.open("#{output_dir}/#{table_name}.yml", 'w') do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name.upcase)
file.write data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
puts "wrote #{table_name} to #{output_dir}/"
end
end
end
end
Source: http://sachachua.com/blog/2011/05/rails-exporting-data-specific-tables-fixtures/
Note: I had to make a few changes to the blog code to make it more cross-database compatible and work in Rails 3.2