ネストが深いjson(ハッシュ)データの各値ををDBに入れたいのですがうまく入りません。
data= { {"id"=>"1, "country_id"=>"169", "country_name"=>"England", "league_id"=>"62", "lineup"=>{ "home"=>{"starting_lineups"=>[], "substitutions"=>[]}, "away"=>{"starting_lineups"=>[], "substitutions"=>[]} }, "statistics"=>[]}, . .省略 . {"id"=>"20", "country_id"=>"169", "country_name"=>"England", "league_id"=>"62", "lineup"=>{ "home"=>{"starting_lineups"=>[], "substitutions"=>[]}, "away"=>{"starting_lineups"=>[], "substitutions"=>[]} }, "statistics"=>[]} }
以上のような配列に入ったjsonデータをtablesというテーブルにまとめて入れたいです。
今行なっていることは、まず"lineup=>"以下の値が入れ子になっている為、
home = nil away = nil data.each do |detail| b = detail['lineup'] home = b.assoc('home').pop away = b.assoc('away').pop end
とし変数homeとawayにそれぞれキーhome,awayの値を入れております。
そして、home、awayとそれ以外のハッシュの値をまとめてtablesというテーブルに入れたいのでzipメソッドを使ってまとめて、ブロック内でcreateメソッドを用いております。
team_data.zip(home,away).each do |detail1,detail2,detail3| Table.create(match_id:detail1['match_id'], country_id:detail1['country_id'], country_name:detail1['country_name'],league_id:detail1['league_id'], lineup_h:detail2['starting_lineups'],lineup_a:detail3['starting_lineups'], substitute_h:detail2['substitutions'],substitute_a:detail3['substitutions'] end
というようにコードを書いております。
以上のコードはrakeファイルでtaskとして定義している為、コンソール画面でrake taskコマンドを打ちログを見るとno implicit conversion of String into Integerとエラーが出ていて、怒られている箇所はブロック変数detail2やdetail3といったhome,awayの値をカラムに入れている箇所です。
zipメソッドに関しては自力で見つけ使っているもので、使い方がまだあやふやな面がございますのでエラーが出ている理由がわからないのですが何が問題なのでしょうか。
ちなみにカラムの型は全てstringで定義しており、またstarting_lineupsやsubstitutionsの値は見て通りではありますが配列として複数の値が入る予定です。
少し長くなりましたがご回答いただけると幸いです。宜しくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/28 08:09
2018/08/28 17:38
2018/08/29 02:00