krn*_*krn 16 activerecord ruby-on-rails
如何使用YAML文件而不是seeds.rb将初始数据加载到数据库中?
Zaz*_*Zaz 23
添加代码db/seeds.rb以解析YAML文件,例如:
seed_file = Rails.root.join('db', 'seeds', 'categories.yml')
config = YAML::load_file(seed_file)
Category.create!(config)
Run Code Online (Sandbox Code Playgroud)
然后,只需将YAML放入db/seeds/categories.yml.YAML文件应该是关联数组的列表,例如:
- name: accessory
shortcode: A
- name: laptop
shortcode: L
- name: server
shortcode: S
Run Code Online (Sandbox Code Playgroud)
我使用了@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
Run Code Online (Sandbox Code Playgroud)
查看 Ruby on Rails 装置指南:
http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures
通常,您可以在test/目录中创建 YAML 固定文件,然后使用命令将它们加载到数据库中rake db:fixtures:load。关于您可以使用灯具做的所有很酷的事情的完整文档在这里:
http://api.rubyonrails.org/classes/Fixtures.html
| 归档时间: |
|
| 查看次数: |
10174 次 |
| 最近记录: |