我在通过散列解析并将某些部分保存到数据库时遇到了问题。我可以遍历它来获取我需要的信息。我的问题是更新我的数据库中的记录。我试图根据每个国家的国家代码是否与XML解析中的国家/地区代码相匹配来更新数据库中的现有记录。在Rails中更新记录时未定义的方法更新
在我的控制,我有:
class CountriesController < ApplicationController
def index
@countries = Country.all
travel_alerts = request_data('http://travel.state.gov/_res/rss/TAs.xml')
travel_warnings = request_data('http://travel.state.gov/_res/rss/TWs.xml')
# Sets warnings
warnings_array = travel_warnings["rss"]["channel"]["item"]
warnings_array.each do |warning|
@country = Country.find_by(code: warning["identifier"].strip)
@country.update(title: warning["title"],
description: warning["description"])
end
end
end
...
我使用.update和.save试过,但没有作品。当我尝试更新时,我得到:
undefined method `update' for nil:NilClass
更新方法是否需要在Country模型中显式定义?如果是这样,那么在控制器中完成分析信息的最佳方式是什么?
这只是意味着'Country.find_by(代码:warning [“identifier”]。strip)'找不到任何东西,所以'@ country'将是Nil,而Nil没有更新方法。在尝试更新前,你可能想验证'@ country'不是零。 '除非@ country.nil? @ country.update(etc ...)' – Clark