APIからJSONネストされたハッシュ(またはハッシュの配列)を取得しているとしましょう
@example = {"results" = > {{"poop" => "shoop"},{"foo" => {"shizz" => "fizz", "nizzle"=>"bizzle"}}}
上記のネストされたハッシュのYAMLマークアップ
- poop: shoop
- foo:
shizz: fizz
nizzle: bizzle
それでは、ハッシュからActiveRecordを使用してdbエントリを作成しましょう。これは正常に機能します。
Thing.create!(:poop => @example["results"]["poop"],
:shizz => @example["results"]["foo"]["shizz"],
:nizzle=> @example["results"]["foo"]["nizzle"])
しかし、「foo」が空またはnilの場合はどうなりますか?たとえば、APIの結果に「名」、「姓」#などの「人」ハッシュが含まれている場合、データがない場合、「人」ハッシュは通常空になります。つまり、その中のハッシュは空になりません。存在。
@example = {"results" = > {{"poop" => "shoop"},{"foo" => nil }}
Thing.create!(:poop => @example["results"]["poop"],
:shizz => @example["results"]["foo"]["shizz"],
:nizzle=> @example["results"]["foo"]["nizzle"])
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
これを処理するための最良の方法は何ですか?