首页 文章

在Rails中更新记录时未定义的方法更新

提问于
浏览
0

我在解析哈希然后将某些部分保存到我的数据库时遇到问题 . 我能够遍历它以获取我需要的信息 . 我的问题是更新我的数据库中的记录 . 我正在尝试根据每个国家/地区的国家/地区代码是否与XML解析中的国家/地区代码匹配来更新数据库中的现有记录 .

在我的控制器中,我有:

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 回答

  • 1

    它引发了一个错误,因为找不到给定代码的 Country ,然后 find_by 返回 nil ,其中不存在更新方法 .

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

    如果预计某些国家/地区不存在,请将更新语句放在if块中

    if @country
      @country.update ... 
    end
    

相关问题