2017-02-05 87 views
1

我是ruby-newbie,我需要從YAML播種我的數據庫。在seeds.rb加載YAML後我得到這個數組的哈希:從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)) 

如何我可以遍歷並創建新的項目和託多斯?請幫忙!

回答

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 
+0

太謝謝你了! – GreenSpike