0

我正在尝试使用 resque gem 生成 xml 文件作为后台任务,这里是生成 xml 文件的类....

ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV']
require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
require  'rubygems'
require 'builder'

class GenerateXml
  @queue = :worker

  def self.perform
    file_name = "#{Time.now.strftime('%Y_%m_%d')}_export.xml"

    xml = Builder::XmlMarkup.new(:target => file_name, :indent => 2)
    xml.instruct!(:xml, :encoding => "UTF-8")

    xml.Postings do
      Result.find_in_batches do |result|
        xml.Posting do
          xml.JobID result.job_id
          xml.JobURL result.job_url
        end
      end
    end
  end
end

我从中提取xml标签字段的结果模型是这样的

require 'active_record'

class Result < ActiveRecord::Base
  def job_id
    self.link
  end

  def job_url
    self.link
  end
end

我的问题是为什么类中的 result.job_url 和 result.job_idGenerateXml无法Result正确映射到类?

还有一件事,Result该类位于 app/models 目录下,而GenerateXml类位于 lib/jobs 目录下

这是错误的痕迹。

      undefined method `job_id' for #<Array:0xb3f26738>

/home/netserv/RubymineProjects/crawler/lib/jobs/generate_xml.rb:22:in `perform'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:155:in `call'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:155:in `_nested_structures'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:63:in `method_missing'
/home/netserv/RubymineProjects/crawler/lib/jobs/generate_xml.rb:21:in `perform'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/activerecord-3.2.3/lib/active_record/relation/batches.rb:72:in `find_in_batches'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/activerecord-3.2.3/lib/active_record/querying.rb:8:in `__send__'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/activerecord-3.2.3/lib/active_record/querying.rb:8:in `find_in_batches'
/home/netserv/RubymineProjects/crawler/lib/jobs/generate_xml.rb:20:in `perform'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:155:in `call'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:155:in `_nested_structures'
/home/netserv/.rvm/gems/ruby-1.8.7-p357/gems/builder-3.0.0/lib/builder/xmlbase.rb:63:in `method_missing'
/home/netserv/RubymineProjects/crawler/lib/jobs/generate_xml.rb:19:in `perform'
4

2 回答 2

2

find_in_batches 返回数组。在Postings块内,您可以这样做:

  Result.find_in_batches do |results|
    results.each do
      xml.Posting do
        xml.JobID result.job_id
        xml.JobURL result.job_url
      end
    end
  end

但为什么还要费心find_in_batches呢?

于 2012-05-14T12:01:49.547 回答
0

find_in_batches正在返回一个 Array

你必须更新或创建一个特定的Result而不是更新一个Arrayof Results,这意味着什么。

于 2012-05-14T12:02:45.707 回答