简体   繁体   English

如何使用 yaml 文件中的数据为数据库做种? 轨道上的红宝石

[英]How to seed database with data from yaml file? Ruby on rails

I need to fill my database with data from yaml file, which contains something like:我需要用 yaml 文件中的数据填充我的数据库,其中包含以下内容:

-Users:
------Users_nameship: 'First group'
------Members:
----------Name:'Jack'

etc. And i need to use seeds.rb file For now i make something like that:等等,我需要使用seeds.rb文件现在我做这样的事情:

    require 'yaml'

    seed_file = Rails.root.join('db', 'seeds.yml')
    @config = Hash.new(YAML::load_file(seed_file))
    @config.each do |key, values|
        values.each do |k,v|
            Project.create title:v
        end
    end

But its dont fill any cell in table.但它不填充表格中的任何单元格。 Please help请帮忙

Yaml files are used by fixtures for testing purposes.夹具使用 Yaml 文件进行测试。 On the other hand, you can use db/seed.rb to populate your db with the following command:另一方面,您可以使用 db/seed.rb 使用以下命令填充您的数据库:

rake db:seed

Check the following models:检查以下型号:

class Group < ApplicationRecord
  has_many :users
end

class User < ApplicationRecord
  belongs_to :group
end

You could generate two groups with two users each with the following seed.rb file:您可以生成两个包含两个用户的组,每个组使用以下 seed.rb 文件:

Group.create!([{name: "First group"}, {name: "Second group"}])

User.create!([{name: 'Jack', group_id: 1}, {name: 'Bob', group_id: 1}, {name: 'Robert', group_id: 2}, {name: 'John', group_id: 2}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM