2015-05-18 70 views
0

我在通过散列解析并将某些部分保存到数据库时遇到了问题。我可以遍历它来获取我需要的信息。我的问题是更新我的数据库中的记录。我试图根据每个国家的国家代码是否与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模型中显式定义?如果是这样,那么在控制器中完成分析信息的最佳方式是什么?

+1

这只是意味着'Country.find_by(代码:warning [“identifier”]。strip)'找不到任何东西,所以'@ country'将是Nil,而Nil没有更新方法。在尝试更新前,你可能想验证'@ country'不是零。 '除非@ country.nil? @ country.update(etc ...)' – Clark

回答

1

它会产生错误,因为Country找不到给定的代码,则find_by返回nil,其上不存在更新方法。

而不是find_by executrun find_by! - 你应该得到ActiveRecord::RecordNotFound error

如果预计有些国家根本不存在把你的更新语句中,如果块

if @country 
    @country.update ... 
end 
+0

太好了,谢谢!将它包含在更新声明中工作(让我疯狂,试图找出它)。感谢帮助! – hidace