Activerecord 3.2.8关联错误

时间:2012-09-26 19:43:50

标签: ruby multithreading activerecord

我使用此代码遇到了ActiveRecord 3.2.8的奇怪错误:

我有2个型号 - 客户和发票。

class Customer < ActiveRecord::Base
  has_many :invoices
end

class Invoice < ActiveRecord::Base
  belongs_to :customer

  def self.last(customer)
    customer.invoices.order("some_date_column DESC").first
  end
end

我正在运行类似的代码:

Thread.new do
  ActiveRecord::Base.connection_pool.with_connection do
    Customer.all.each do |customer|
      invoice = Invoice.last(customer)
      ...
    end
  end
end

运行该代码时,我有时会遇到以下奇怪错误:

/var/lib/gems/1.8/gems/activerecord-3.2.8/lib/active_record/associations/collection_association.rb:25:in 'initialize': wrong number of arguments (1 for 0) (ArgumentError)
from /var/lib/gems/1.8/gems/activerecord-3.2.8/lib/active_record/associations/collection_association.rb:25:in 'new'
from /var/lib/gems/1.8/gems/activerecord-3.2.8/lib/active_record/associations/collection_association.rb:25:in 'initialize'
from /var/lib/gems/1.8/gems/activerecord-3.2.8/lib/active_record/associations.rb:157:in 'new'
from /var/lib/gems/1.8/gems/activerecord-3.2.8/lib/active_record/associations.rb:157:in 'association'
from /var/lib/gems/1.8/gems/activerecord-3.2.8/lib/active_record/associations/builder/association.rb:44:in 'invoices'
from .../models/invoice.rb:7:in 'last'

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

当你遇到这种错误时

wrong number of arguments (X for Y)

这意味着您尝试调用传递的参数不同于预期的方法。在您的情况下,您调用的方法不应该接收任何参数(for 0),但您尝试传递一个(1 for)。从错误的最后一行开始,问题似乎是Invoice.last(customer)