简体   繁体   English

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

[英]Ruby on Rails: loading seed data from a YAML file

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

Add code in db/seeds.rb to parse the YAML file, eg:db/seeds.rb添加代码来解析 YAML 文件,例如:

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

Then, simply place the YAML fie in db/seeds/categories.yml .然后,只需将 YAML 文件放在db/seeds/categories.yml The YAML file should be a list of associative arrays, eg: YAML 文件应该是关联数组的列表,例如:

- name: accessory
  shortcode: A

- name: laptop
  shortcode: L

- name: server
  shortcode: S

I used the answer @Zaz answered.我使用了@Zaz 回答的答案。 It works very well.它运作良好。

But in the meanwhile if something went wrong with your seed data(For example you have a very large seed yaml file), you would like to know which part of your yaml went wrong.但与此同时,如果您的种子数据出现问题(例如您有一个非常大的种子 yaml 文件),您想知道您的 yaml 的哪一部分出了问题。 At that time you can add a block after create!到时候你可以在创建后添加一个块! for debug like this:对于这样的调试:

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

Check out the Ruby on Rails Guide to fixtures:查看 Ruby on Rails 固定装置指南:

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

Generally, you can create YAML fixture files in the test/ directory and then load them into your database using the rake db:fixtures:load command.通常,您可以在test/目录中创建 YAML 夹具文件,然后使用rake db:fixtures:load命令将它们加载到您的数据库中。 The full documentation on all the cool things you can do with fixtures is here:关于你可以用夹具做的所有很酷的事情的完整文档在这里:

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

I built this script to handle exactly this issue, while keeping seeds yaml files separate to tests.我构建了这个脚本来处理这个问题,同时将种子 yaml 文件与测试分开。

It has namespace support, and will automatically find records when you supply just an id它有命名空间支持,当你只提供一个 id 时会自动查找记录

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM