Ruby on Rails:从YAML文件加载种子数据

如何使用YAML文件而不是seeds.rb将初始数据加载到数据库中?

查看固定装置的Ruby on Rails指南:

http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures

通常,您可以在test/目录中创建YAML fixture文件,然后使用rake db:fixtures:load命令将它们加载到数据库中。 关于灯具可以做的所有很酷的事情的完整文档在这里:

http://api.rubyonrails.org/classes/Fixtures.html

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文件应该是关联数组的列表,例如:

 - name: accessory shortcode: A - name: laptop shortcode: L - name: server shortcode: S 

我用答案@Zaz回答。 它工作得很好。

但同时如果您的种子数据出现问题(例如,您有一个非常大的种子yaml文件),您想知道您的yaml哪个部分出错了。 那时你可以在创建后添加一个块! 像这样的调试:

 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