dace
dace

Reputation: 6363

Undefined method update when updating a record in Rails

I'm having trouble parsing through a hash and then saving certain parts to my database. I'm able to iterate through it to get to the information that I need. My problem is updating the record in my database. I'm trying to update an existing record in my database based on if the country code for each country matches the country code in the XML parse.

In my controller I have:

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

...

I've tried using .update and .save, but neither works. When I try update I get:

undefined method `update' for nil:NilClass

Does the update method need to be explicitly defined in the Country model? If so, what's the best way to have access to the parsed information since that's being done in the controller?

Upvotes: 0

Views: 1532

Answers (1)

djaszczurowski
djaszczurowski

Reputation: 4515

It raises an error, because Country by given code was not found, then find_by returns nil, on which update method does not exist.

Instead of find_by executrun find_by! - you should get ActiveRecord::RecordNotFound error

If it is expected some countries do not exist put your update statement within if block

if @country
  @country.update ... 
end

Upvotes: 1

Related Questions