将现在的数据库记录生成fixture数据文件

desc 'generate yml data file from current development database'

task :generate_fixture => :environment do
  ActiveRecord::Base.establish_connection

  table_name = STDIN.gets.chomp
  raise "fixtures file of #{table_name} alreay exist!" if File.exist?("#{RAILS_ROOT}/spec/fixtures/#{table_name}.yml")
  i= "000"
  File.open("#{RAILS_ROOT}/spec/fixtures/#{table_name}.yml", 'w') do |file|
    data = ActiveRecord::Base.connection.select_all("SELECT * FROM #{table_name} where rownum < 5 order by id desc ")
    file.write data.inject({}) { |hash, record|
      hash["#{table_name}_#{i.succ!}"] = record
      hash
    }.to_yaml
  end
end

你可能感兴趣的:(Ruby,ActiveRecord,Rails)