0

我编写了一个 rake 任务来将 XML 提要导入我的 ActiveRecord 模型,但遇到了一些麻烦 - XML 提要不会发布任何空列,这会破坏我的迁移工具。如何设计我的导入器以使其跳过空白字段?

我的进口商看起来像这样

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,

    ....

假设“desc”在 xml 提要中不可用。我希望我的代码在这种情况下忽略“desc”。

错误信息是无用的:

undefined method `text' for nil:NilClass

但它与文本方法无关。

4

2 回答 2

0

您可以使用try 方法

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),

    ....

医生说:

如果接收对象是 nil 对象或 NilClass:将不会引发 NoMethodError 异常,而是返回 nil。

于 2012-11-15T22:23:54.563 回答
0

我会在 Nokogiri 查询中查找文本:

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

    ...

如果元素不存在,这不会引发异常。

于 2012-11-16T02:04:49.337 回答