来自YAML的播种数据库

时间:2017-02-05 17:56:46

标签: ruby-on-rails ruby

我是ruby-newbie,我需要从YAML播种我的数据库。在seeds.rb中加载YAML后,我得到了这个哈希数组:

{"projects"=>[{"title"=>"Family", "todos"=>[{"text"=>"buy a milk", "isCompleted"=>false},
 {"text"=>"Change oil in engine", "isCompleted"=>false},
 {"text"=>"To send the letter", "isCompleted"=>true},
 {"text"=>"To drink smt", "isCompleted"=>false}, {"text"=>"Buy t-shirt", "isCompleted"=>false}]},
 {"title"=>"Job", "todos"=>[{"text"=>"Call chief", "isCompleted"=>true},
 {"text"=>"To send documents", "isCompleted"=>true},
 {"text"=>"Make todolist", "isCompleted"=>false}]},
 {"title"=>"Other", "todos"=>[{"text"=>"To call friend", "isCompleted"=>false},
 {"text"=>"Prepare for trip", "isCompleted"=>false}]}]}

我的代码:

seed_file = Rails.root.join('db', 'seeds', 'seeds.yml')
config = HashWithIndifferentAccess.new(YAML::load_file(seed_file))

我如何迭代它并创建新项目和Todos?请帮忙!

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作来迭代每个项目和待办事项:

my_hash设置为您拥有的哈希值,然后

my_hash[“projects”].each do |project|

  # do whatever you need to do with each item in the hash e.g.
  puts project[“title”]

  # then to get the todos…
  project[“todos”].each do |todo|
    puts todo[“text”]
  end
end

答案 1 :(得分:0)

最简单的方法是将YAML种子文件放入db / seeds /中,然后将其放入db / seeds.rb文件中:

img_inputs = keras.Input(shape=(32, 32, 3))

这将以与测试期间加载夹具相同的方式加载所有种子。