How to generate fixtures based on my development database?

后端 未结 3 1032
花落未央
花落未央 2021-02-05 04:07

I\'m lazy and I since my production database has data I could use for testing through on going development, I was wondering if there were any easy methods of ge

3条回答
  •  抹茶落季
    2021-02-05 04:52

    In case you're creating a script to run under rails runner you can use the following approach:

    File.open("#{Rails.root}/spec/fixtures/documents.yml", 'w') do |file|
      file.write Document.all.to_a.map(&:attributes).to_yaml
    end
    

    you can create as much blocks as you want, or if you want to go to the full database you can try:

    models = defined?(AppicationRecord) ? ApplicationRecord.decendants : ActiveRecord::Base.descendants
    models.each do |model|
      model_name = model.name.pluralize.underscore
      File.open("#{Rails.root}/spec/fixtures/#{model_name}.yml", 'w') do |file|
        file.write model.all.to_a.map(&:attributes).to_yaml
      end
    end
    

    if you do not want the timestamps you can change the code to: model.all.to_a.map { |m| m.attributes.except('created_at', 'updated_at')}.to_yaml

提交回复
热议问题