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

时间:2011-08-08 18:03:40

标签: ruby-on-rails activerecord

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

4 个答案:

答案 0 :(得分:22)

db/seeds.rb中添加代码以解析YAML文件,例如:

seed_file = Rails.root.join('db', 'seeds', 'categories.yml')
config = YAML::load_file(seed_file)
Category.create!(config)

然后,只需将YAML fie放入db/seeds/categories.yml即可。 YAML文件应该是关联数组的列表,例如:

- name: accessory
  shortcode: A

- name: laptop
  shortcode: L

- name: server
  shortcode: S

答案 1 :(得分:4)

查看固定装置的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

答案 2 :(得分:2)

我用@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

答案 3 :(得分:0)

我构建了此脚本来处理此问题,同时将种子yaml文件与测试分开。

它具有名称空间支持,当您仅提供ID时将自动查找记录

https://gist.github.com/x9sim9/78405f13b698b87ab7b234ea793399ca