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

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)

  • 如果向表中添加新的种子值或添加具有种子值的新表.删除整个数据库可能是开发环境中的解决方案,但肯定不是生产环境.如果在另一个表中有对该表的ID的引用,则在重新播种之前删除种子表也不是一种选择.如果您需要删除以前播种的值,情况会变得更加复杂,并且可能需要超出"rake db:seed"的解决方案. (2认同)

art*_*ant 5

我使用了@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)


Nub*_*uby 2

查看 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

  • 最后一个链接已损坏。此外,从“test/”加载种子数据似乎不是正确的做法。 (3认同)