Ruby on Rails: loading seed data from a YAML file

后端 未结 4 910
礼貌的吻别
礼貌的吻别 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:12

    Check out the Ruby on Rails Guide to fixtures:

    http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures

    Generally, you can create YAML fixture files in the test/ directory and then load them into your database using the rake db:fixtures:load command. The full documentation on all the cool things you can do with fixtures is here:

    http://api.rubyonrails.org/classes/Fixtures.html

    0 讨论(0)
  • 2020-12-28 18:13

    I built this script to handle exactly this issue, while keeping seeds yaml files separate to tests.

    It has namespace support, and will automatically find records when you supply just an id

    https://gist.github.com/x9sim9/78405f13b698b87ab7b234ea793399ca

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-28 18:27

    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
    
    0 讨论(0)
提交回复
热议问题