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

三世轮回 提交于 2019-12-02 15:24:01

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!