Ruby on Rails: loading seed data from a YAML file

后端 未结 4 911
礼貌的吻别
礼貌的吻别 2020-12-28 18:04

How do I use a YAML file instead of seeds.rb to load the initial data into a database?

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 18:19

    I used the answer @Zaz answered. 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. 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
    

提交回复
热议问题