如何使用seed.rb有选择地填充开发和/或生产数据库?

Dar*_*rme 51 environment ruby-on-rails ruby-on-rails-3

我正在使用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) 
Run Code Online (Sandbox Code Playgroud)

这样就可以调用特定于开发的代码和非特定代码

$ rake db:seed
Run Code Online (Sandbox Code Playgroud)

并使用以下命令调用特定于生产的代码和非特定代码:

$ rake db:seed RAILS_ENV=production 
Run Code Online (Sandbox Code Playgroud)

谢谢

cam*_*cam 72

seeds.rb只是一个简单的ruby文件,因此有几种方法可以解决这个问题.案件陈述怎么样?

# do common stuff here

case Rails.env
when "development"
   ...
when "production"
   ...
end
Run Code Online (Sandbox Code Playgroud)


fab*_*bro 36

另一种方法可能是:

db/seeds/development.rb
db/seeds/production.rb
db/seeds/any_other_environment.rb
Run Code Online (Sandbox Code Playgroud)

然后在db/seeds.rb:

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

然后在相应的文件中编写要为每个环境运行的代码.

  • 不错.发现这很有用,但我不想种子测试所以你需要有一个空的种子/ test.rb文件,或者你可以捕获未找到的文件(以及其他错误),所以它不会终止测试. (2认同)

yos*_*ico 10

另一种方法,与@ fabro的答案非常相似:db/使用环境名称和另一个名为common.rb 的文件夹添加文件夹种子,因此您可以获得如下内容:

db/seeds/common.rb
db/seeds/development.rb
db/seeds/staging.rb
db/seeds/production.rb
Run Code Online (Sandbox Code Playgroud)

比你的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
Run Code Online (Sandbox Code Playgroud)

我更喜欢在一次交易中运行种子

  • 两周前的事情仍然具有相关性和帮助性,这是一个美妙的时刻。一定会喜欢 Rails 的成熟 (2认同)
  • @zcserei *年 (2认同)