2015-05-18 64 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