NoMethodError:未定义的方法`<<'为零:NilClass

时间:2014-07-23 18:12:20

标签: ruby-on-rails ruby

我有一项任务,我没有建立,但不再工作。我是ruby on rails的新手,还没有找到解决这个问题的方法。

当我运行任务时我得到:

这是任务:

  desc "Archive Loads/Trucks that have expired."
  task :expire_old_posts => :environment do
    expired_loads = []
    loads = Load.where("pickup < NOW()")
    loads.each {|load| expired_loads << load.attributes } 
    ArchivedLoad.create( expired_loads )
    loads.delete_all
  end

通过控制台进行小调试

确认有120530个转移负荷:

loads = Load.where("pickup < NOW()").count    
2014-07-23 12:55:56 DEBUG --    (149.8ms)  SELECT COUNT(*) FROM "loads" WHERE (pickup < NOW())
 => 120530

创建空数组:

expired_loads = []
=> []

运行where命令

loads = Load.where("pickup < NOW()")

很多很多记录......我把它限制在两个用于测试

1.9.3-p547 :006 > loads = Load.where("pickup < NOW()").limit(2)
2014-07-23 13:02:07 DEBUG --   Load Load (74.2ms)  SELECT "loads".* FROM "loads" WHERE (pickup < NOW()) LIMIT 2
 => [#<Load id: 18398947, user_id: 11074, origin: #<RGeo::Geographic::SphericalPointImpl:0x595f056 "POINT (-80.48237609863281 37.772544860839844)">, dest: #<RGeo::Geographic::SphericalPointImpl:0x595ec64 "POINT (-78.30302429199219 40.295894622802734)">, length: 48, comments: "~PostEverywhere_20140721140916~", ltl: false, rate: nil, delivery: "2014-07-22 17:00:00", pickup: "2014-07-21 17:00:00", weight: 48, equipment_id: 8, covered: false, created_at: "2014-07-21 19:16:16", updated_at: "2014-07-21 19:16:16", owner: nil, deleted: false, origin_city: "ronceverte", origin_state: "wv", dest_city: "martinsburg", dest_state: "pa">, #<Load id: 18398948, user_id: 11074, origin: #<RGeo::Geographic::SphericalPointImpl:0x553cd2a "POINT (-81.035400390625 37.384891510009766)">, dest: #<RGeo::Geographic::SphericalPointImpl:0x553c9d8 "POINT (-79.80570983886719 40.317527770996094)">, length: 48, comments: "~PostEverywhere_20140721140916~", ltl: false, rate: nil, delivery: "2014-07-22 17:00:00", pickup: "2014-07-21 17:00:00", weight: 48, equipment_id: 8, covered: false, created_at: "2014-07-21 19:16:16", updated_at: "2014-07-21 19:16:16", owner: nil, deleted: false, origin_city: "princeton", origin_state: "wv", dest_city: "greenock", dest_state: "pa">] 

真的不确定&lt;&lt;但我认为这只是分配属性,以便它们可以保存在另一个表

loads.each {|load| expired_loads << load.attributes } 

此处有错误

**NoMethodError: undefined method `<<' for nil:NilClass**

下一行是:将它们保存到archived_loads表并从load表中删除

ArchivedLoad.create( expired_loads )
loads.delete_all

1 个答案:

答案 0 :(得分:0)

为什么不使用#map呢? expired_loads = loads.map(&:attributes)或者更好,只需在Load中创建一个方法来存档它们,例如

class Load
  scope :expired_loads, -> {where("pickup < NOW()")}
  def self.archive_now
    ArchiveLoad.create(expired_loads.map(&:attributes))
    expired_loads.delete_all
  end        
end

然后你可以致电Loads.archive_now我不确定你的任何结构这只是一个更简洁的实施建议。

如果您在其中使用create方法,也可能谨慎地发布ArchivedLoad <<方法。如果您还没有实现某种自定义create方法,我认为您需要迭代,例如

expired_loads.map(&:attributes).each{|load| ArchiveLoad.create(load)}

同样<<类似于push它将对象添加到Array

的末尾