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
命令将它们加载到数据库中。 关于灯具可以做的所有很酷的事情的完整文档在这里:
在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
- 如何在更新的Rails上通过readonly替换find?
- 所有在数组中的PostgreSQL
- 在Rails应用程序中的查询运行时更改表名
- HMT collection_singular_ids =删除连接模型是直接的,不会触发销毁回调
- 升级到Rails 3.2.2:如何解决与Delayed Job gem相关的’未定义的Syck :: DomainType方法’错误?
- 这个Rails4错误是什么意思? 致命:exception重新进入……“在rollback_active_record_state中救援!”
- 在RoR中将简单查询转换为棘手的命名范围
- 查找符合所有类别的产品(Rails 3.1)
- ActiveRecord加入聚合查询