【发布时间】:2017-08-01 08:02:05
【问题描述】:
我有想要导入数据库的 xml 数据。我正在尝试使用 nokogiri 宝石。我编写了一个名为 xml_data.rb 的文件。当我在命令行上运行>ruby xml_data.rb 时,我收到以下错误:
xml_data.rb:8:in
block in <main>': uninitialized constant Job (NameError) from C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/nokogiri-1.7.0.1-x86-mingw32/lib/nokogiri/xml/node_set.rb:187:inblock in each' 来自 C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/nokogiri-1.7.0.1-x86-mingw32/lib/nokogiri/xml/node_set.rb:186:inupto' from C:/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/nokogiri-1.7.0.1-x86-mingw32/lib/nokogiri/xml/node_set.rb:186:ineach' 来自 xml_data.rb:7:in `'
我不确定我是否了解如何正确执行此操作。下面是xml_data.rb文件:
require 'nokogiri'
OLD_DATA = 'data/old_data.xml'
doc = File.open(OLD_DATA) {|f| Nokogiri::XML(f)}
doc.css('request').each do |node|
Job.create(
:last_name => node['name'],
:telephone => node['phone'],
:street_address => node['address'],
:city => node['city'],
:state => node['state'],
:zip => node['zip'],
:email => node['email'],
:au_chog => node['chogAu'],
:person_type => node['affil'],
:research_use => node['use'],
:subject => node['subject'],
:notes => node['note'],
:start_date => node['startDate'],
:end_date => node['addDate'],
:complete => true,
:time_spend => node['hours']
)
end
红宝石:v2.3.3 导轨:v5.0.1
更新
我将这段代码重写为 rake 任务。但是,我没有这样做。当我运行该任务时,我遇到了几个与 XML 语法有关的语法错误,这是正确的。以下是更新后的代码:
require 'nokogiri'
namespace :db do
namespace :seed do
desc 'Add old data to database'
task :import_data => :environment do
OLD_DATA = "#{Rails.root}/lib/assets/data/old_data.xml"
doc = Nokogiri::XML(File.open(OLD_DATA)) do |config|
config.options = Nokogiri::XML::ParseOptions::STRICT
end
doc.css("request").each do |node|
Job.create(
:last_name => node['name'],
:telephone => node['phone'],
:street_address => node['address'],
:city => node['city'],
:state => node['state'],
:zip => node['zip'],
:email => node['email'],
:au_chog => node["chogAu"],
:person_type => node['affil'],
:research_use => node['use'],
:subject => node['subject'],
:notes => node['note'],
:start_date => node['startDate'],
:end_date => node['addDate'],
:complete => true,
:time_spend => node['hours']
)
end
end
end
end
【问题讨论】:
标签: ruby-on-rails ruby xml ruby-on-rails-5 rake-task