我该如何使用YAML文件代替seeds.rb将初始数据加载到数据库中?
我该如何使用YAML文件代替seeds.rb将初始数据加载到数据库中?
在db/seeds.rb
文件中添加代码以解析YAML文件,例如:
seed_file = Rails.root.join('db', 'seeds', 'categories.yml')
config = YAML::load_file(seed_file)
Category.create!(config)
然后,将YAML文件放入db/seeds/categories.yml
中。YAML文件应该是一个关联数组的列表,例如:
然后,只需将YAML文件放置在db/seeds/categories.yml
中。YAML文件应该是一个关联数组的列表,例如:
- name: accessory
shortcode: A
- name: laptop
shortcode: L
- name: server
shortcode: S
rake db:seed
,那么您将获得许多重复项。根据唯一性的要求,您可能需要修改最后一行,使其类似于:config.each {|values| Category.first_or_create(values) }
。 - sberkleyrake db:reset
99% 的时间都可以完成您所需的一切。 - Zazrake seed:migrate
(和回滚)。在种子迁移中,您可以执行各种答案中的标准 yaml 文件加载操作。 - user483040我使用了@Zaz提供的答案,它非常有效。
但是如果您的种子数据出现了问题(例如您有一个非常大的种子yaml文件),您希望知道哪一部分yaml出了问题。这时候,您可以在create!后添加一个调试块,像这样:
seed_file = Rails.root.join('db', 'seeds', 'categories.yml')
config = YAML::load_file(seed_file)
counter = 0
Category.create!(config) do |c|
puts "Create category #{counter += 1} with name: #{c.name}"
end
http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures
通常,您可以在test/
目录中创建YAML fixture文件,然后使用rake db:fixtures:load
命令将它们加载到数据库中。有关fixture的所有功能的完整文档在此处:
https://gist.github.com/x9sim9/78405f13b698b87ab7b234ea793399ca