为什么我会得到"未定义的方法' fetch' for nil:NilClass(NoMethodError)"

时间:2016-10-13 14:25:31

标签: ruby-on-rails json ruby

我正在解析JSON数据以保存到我的数据库。

JSON数据是这样的:

{"id"=>889066,
  "email"=>"new.user@email.com",
  "created_at"=>"2014-10-24T18:46:13Z",
  "updated_at"=>"2014-10-24T18:46:13Z",
  "status"=>"Registered",
  "custom_status"=>nil,
  "first_name"=>New,
  "last_name"=>User,
  "latest_visitor"=>
   {"id"=>16998604, "tracking_code"=>"cab237f6-50ec-4424-9ea9-b0110070a6cb"},
  "url"=>{"id"=>2422287, "url"=>"http://www.website.com/"},
  "referrer"=>{"id"=>4234808, "url"=>"https://www.google.ba/"},
  "affiliate"=>nil,
  "campaign"=>nil,
  "search_term"=>
   {"id"=>344901, "term"=>"puppies", "search_engine"=>"google"},
  "tracking_code"=>"cab237f6-50ec-4424-9ea9-b0110070a6cb"}]

例如,我想获取搜索引擎值,所以我这样做:

json = JSON.parse(response.body)
json.each do |item|
  Model.create(
    search_engine: item.fetch("search_term").fetch("search_engine")
    )
end

这将返回错误:

in 'block in <top (required)>': undefined method 'fetch' for nil:NilClass (NoMethodError)

编辑:以下是puts item.keys的输出:

id
email
created_at
updated_at
status
custom_status
first_name
last_name
latest_visitor
url
referrer
affiliate
campaign
search_term
tracking_code

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您要做的是检测search_term何时为零并对其执行某些操作。

如果你想丢弃它,那很容易

json = JSON.parse(response.body)
json.each do |item|
  search_term = item.fetch("search_term")
  next if search_term.nil?
  Model.create(
    search_engine: search_term.fetch("search_engine")
    )
end

如果您想在没有search_term时提供一些默认的search_engine值:

DEFAULT_SEARCH_ENGINE = "N/A"
json = JSON.parse(response.body)
json.each do |item|
  search_term = item.fetch("search_term")
  if search_term.nil?
    search_engine = DEFAULT_SEARCH_ENGINE
  else
    search_engine = search_term.fetch("search_engine")
  end
  Model.create(
    search_engine: search_engine
    )
end