Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: loading seed data from a YAML file

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

like image 700
krn Avatar asked Aug 08 '11 18:08

krn


1 Answers

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
like image 151
Zaz Avatar answered Oct 04 '22 11:10

Zaz