我编写了一个 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
但它与文本方法无关。