2010-07-20 73 views
0

我目前正試圖從一個xml文件中讀取,該文件記錄了PBS上的作業。我已經succesfullly成功地解析代碼,但我無法在objtects插入到我的數據庫,我收到此錯誤:Ruby libxml解析並插入到數據庫

「你有一個零對象時,你沒想到吧 你可能會認爲一個實例。

require 'xml/libxml' 

class Job < ActiveRecord::Base 

    JOB_DIR = File.join('data', 'jobs') 

    attr_reader :jobid, :user, :group, :jobname, :queue, :ctime 
    attr_reader :qtime, :etime, :start, :owner 

    def initialize(jobid, user, group, jobname, queue, ctime, qtime, etime, start, owner) 
    @jobid, @user, @group, @jobname, @queue = jobid, user, group, jobname, queue 
    @ctime, @qtime, @etime, @start, @owner = ctime, qtime, etime, start, owner 
    end 

    def self.find_all() 
    jobs = [] 
    input_file = "#{JOB_DIR}/1.xml" 
    doc = XML::Document.file(input_file) 
    doc.find('//execution_record').each do |node| 
     jobs << Job.new(
     node.find('jobid').to_a.first.content, 
     node.find('user').to_a.first.content, 
     node.find('group').to_a.first.content, 
     node.find('jobname').to_a.first.content, 
     node.find('queue').to_a.first.content, 
     node.find('ctime').to_a.first.content, 
     node.find('qtime').to_a.first.content, 
     node.find('etime').to_a.first.content, 
     node.find('start').to_a.first.content, 
     node.find('owner').to_a.first.content 

    ) 
    end 
    jobs 
    end 
end 

的我型控制器:

class JobController < ApplicationController 

    def index 
    @jobs = Job.find_all() 
    end 

    def create 
    @jobs = Job.find_all() 
    for job in @jobs 
     job.save 
    end 
    end 

end 
的的ActiveRecord :: Base的同時評估nil.delete」

這是我的模型時發生錯誤10

我將不勝感激任何幫助......謝謝!

回答

1

我不確定您看到的錯誤消息的原因,因爲我看不到您嘗試調用delete方法的任何地方,但這看起來像是ActiveRecord的一個稍微混淆的用法。

如果你有一個領域jobidusergroupjobname等等,那麼ActiveRecord的將創建這些存取方法,你不應該使用attr_reader或壓倒一切的initialize一個jobs數據庫表。你也應該不會設置值值實例變量(@jobid等),如果您沒有對你的桌子等領域則是沒有在當前的代碼將值從XML數據庫字段映射。

def self.find_all方法大概應該是沿着線:

def self.build_from_xml 
    jobs = [] 
    input_file = "#{JOB_DIR}/1.xml" 
    doc = XML::Document.file(input_file) 
    doc.find('//execution_record').each do |node| 
    jobs << Job.new(
     :jobid => node.find('jobid').to_a.first.content, 
     :user => node.find('user').to_a.first.content, 
    ... 

Rails的使用有它自己find_all的方法來檢索數據庫中的所有現有記錄,這樣你的方法名稱可能是有點誤導。軌往往使用構建動詞意味着創建新模型對象,但不保存它尚未所以這就是爲什麼我與像build_from_xml一個名字了。

+0

謝謝Mikej,這非常有幫助! – jalagrange 2010-07-20 14:02:04

+0

@jalagrange我知道你已經接受了答案,但我不覺得我已經幫了你很多 - 隨時發佈任何後續問題,當你進一步瞭解。 – mikej 2010-07-20 14:15:27