我使用seed.rb来填充我的开发和生产数据库。我通常用虚拟数据填充第一个,用我的应用程序运行所需的真实的最小数据填充后者(例如,第一个用户等等)。
如何在seed.rb中指定每个数据的环境?
鉴于我知道"group“是一个Gemfile方法,我想为seed.rb实现同样的行为。
例如,我想在我的seed.rb中写下这样的东西:
group :development do
# development specific seeding code
end
group :production do
# production specific seeding code
end
# non-specific seeding code (it always runs) 来调用特定于开发的代码和非特定于开发的代码
$ rake db:seed并使用以下命令调用特定于生产的代码和非特定的代码:
$ rake db:seed RAILS_ENV=production 谢谢
发布于 2011-12-29 06:47:42
seeds.rb只是一个普通的ruby文件,所以有几种方法可以解决这个问题。案例陈述如何?
# do common stuff here
case Rails.env
when "development"
...
when "production"
...
end发布于 2015-01-14 03:23:20
另一种方法可能是创建:
db/seeds/development.rb
db/seeds/production.rb
db/seeds/any_other_environment.rb然后在db/seeds.rb中
# Code you want to run in all environments HERE
# ...
load(Rails.root.join( 'db', 'seeds', "#{Rails.env.downcase}.rb"))然后在相应的文件中编写要为每个环境运行的代码。
发布于 2017-01-30 20:45:40
另一种方法,与@fabro的答案非常相似:将一个带有环境名称的文件夹种子和另一个名为common.rb的文件夹种子添加到db/,这样您就会得到类似如下的结果:
db/seeds/common.rb
db/seeds/development.rb
db/seeds/staging.rb
db/seeds/production.rb在你的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我更喜欢在一个事务中运行种子
https://stackoverflow.com/questions/8662127
复制相似问题