简体   繁体   中英

Import error when I save an XML feed to my database using a rake task and Nokogiri

I have written a rake task to import an XML feed into my ActiveRecord model but am running into some trouble - the XML feed will not publish any columns that are empty and this breaks my migration tool. How can I design my importer so it skips over the empty fields?

My importer looks something like this

desc "Import XML Feed into Items Database v20121116" 
task :new_import_items => :environment do

require 'nokogiri'
require 'open-uri'

doc = Nokogiri::XML(File.open("#{Rails.root}/lib/tasks/datafeed.xml"))

actions = doc.xpath("/merchantProductFeed/merchant/prod") 

actions.each do |action|

a = Item.where("affiliate_product_id = ?", action.css("pId").text).first


if a != nil

  a.update_attributes(

    :brand => action.at('brandName').text, 
    :description => action.at('desc').text, 
    :regular_price => action.at('buynow').text,

    ....

Let's say "desc" is not available on the xml feed. I'd like my code to ignore "desc" in that instance.

The error message is useless:

undefined method `text' for nil:NilClass

But it has nothing to do with the text method.

You can use the try method :

if a != nil
  a.update_attributes(
    :brand => action.at('brandName').try(:text), 
    :description => action.at('desc').try(:text), 
    :regular_price => action.at('buynow').try(:text),

    ....

The doc says:

If the receiving object is a nil object or NilClass: a NoMethodError exception will not be raised and nil will be returned instead.

I'd look for the text in the Nokogiri query:

if a != nil
  a.update_attributes(
    :brand => action.at('brandName/text()'), 
    :description => action.at('desc/text()'), 
    :regular_price => action.at('buynow/text()'),

    ...

This will not throw an exception if the element doesn't exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM