是否可以像使用测试和gemfile那样在我的seeds.rb代码中运行一到两个块?
例如,如果我的seeds.rb文件中有以下代码,我可以只对Employee
模型进行种子设定吗?
20.times do
Employee.create!(name: "Bob",
email: Faker::Internet.email)
end
20.times do
User.create!(name: "Hank",
password: "foobar")
end
如果这是我的整个seeds.rb文件,那么当我只想添加更多员工时,运行rake db:seed
将创建20个额外的用户。
您可以在运行rake db:seed
时传递一个选项,如下所示:
rake db:seed users=yes
然后,在您的代码中,您可以通过以下方式访问它:
20.times do
Employee.create!(name: "Bob",
email: Faker::Internet.email)
end
if ENV["users"]
20.times do
User.create!(name: "Hank",
password: "foobar")
end
end
几年来,我一直在使用以下设置来帮助我保持理智。
在db/seeds中,我有以下文件:
001_providers.rb
005_api_users.rb
007_mailing_lists.rb
010_countries.rb
011_us_states.rb
012_canadian_provinces.rb
013_mexican_states.rb
100_world_cities.rb
101_us_zipcodes.rb
我的db/seeds.rb文件如下:
if ENV['VERSION'].present?
seed_files = Dir[File.join(File.dirname(__FILE__), 'seeds', "*#{ENV['VERSION']}*.rb")]
raise "No seed files found matching '#{ENV['VERSION']}'" if seed_files.empty?
else
seed_files = Dir[File.join(File.dirname(__FILE__), 'seeds', '*.rb')]
end
seed_files.sort_by{|f| File.basename(f).to_i}.each do |file|
require File.join(File.dirname(__FILE__), 'seeds', File.basename(file, File.extname(file)))
end
只是一些ruby代码,让我运行一个或多个种子文件。我现在可以做这样的事情:
# run them all
bin/rake db:seed
# run just 001_providers.rb
bin/rake db:seed VERSION=001
# run all seeds for the USA (probably dangerous, but if you name your seeds right, could be useful).
bin/rake db:seed VERSION=us
有一件事非常重要,那就是你的种子文件应该能够一遍又一遍地运行,并以一致的状态结束。如果你一遍又一遍地运行你的种子,你最终会拥有比20个更多的用户。
例如,我的提供者有一个像这样的主循环:
# providers is a hash of attributes...
providers.each_with_index do |(code, attrs), i|
p = Provider.find_by(code: code) || Provider.new(code: code) p.update!(attrs)
end
这样,无论何时运行它,我都能准确地返回我在散列中定义的提供者。