How to use seed.rb to selectively populate development and/or production databases?

前端 未结 3 1737
自闭症患者
自闭症患者 2021-01-30 10:25

I am using seed.rb to populate both my development and production database. I usually populate the first with dummy data and the latter with the real minimal data that my app ne

相关标签:
3条回答
  • 2021-01-30 10:53

    another approach, quite similar to @fabro's answer: add a folder seeds to db/ with the environment names and another named common.rb, so you get something like:

    db/seeds/common.rb
    db/seeds/development.rb
    db/seeds/staging.rb
    db/seeds/production.rb
    

    than, in your seed.rb:

    ActiveRecord::Base.transaction do
      ['common', Rails.env].each do |seedfile|
        seed_file = "#{Rails.root}/db/seeds/#{seedfile}.rb"
        if File.exists?(seed_file)
          puts "- - Seeding data from file: #{seedfile}"
          require seed_file
        end
      end
    end
    

    I perfer running the seed in one transaction

    0 讨论(0)
  • seeds.rb is just a plain ruby file, so there are several ways you could approach this. How about a case statement?

    # do common stuff here
    
    case Rails.env
    when "development"
       ...
    when "production"
       ...
    end
    
    0 讨论(0)
  • 2021-01-30 11:00

    Another approach could be creating:

    db/seeds/development.rb
    db/seeds/production.rb
    db/seeds/any_other_environment.rb
    

    Then in db/seeds.rb:

    # Code you want to run in all environments HERE
    # ...
    load(Rails.root.join( 'db', 'seeds', "#{Rails.env.downcase}.rb"))
    

    Then write the code you want to run for each environment in the respective file.

    0 讨论(0)
提交回复
热议问题