Ruby on Rails: loading seed data from a YAML file
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
Add code in db/seeds.rb
to parse the YAML file, e.g.:
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
. The YAML file should be a list of associative arrays, e.g.:
- name: accessory
shortcode: A
- name: laptop
shortcode: L
- name: server
shortcode: S