undefined方法为true:TrueClass错误

时间:2014-03-18 04:01:47

标签: sql ruby-on-rails activerecord

未定义方法`start_date'表示true:以下控制器操作的TrueClass错误:

@payment = Payment.find(params[:payment_id])
@invoice = @payment.invoice # returns true instead of the invoice object
@start_date = @invoice.start_date.to_time.beginning_of_month # error on method start_date, since @invoice is returning true

当我在控制台中运行相同的代码时:

Payment.find(58)
#<Payment id: 58, amount: 1000.0, method: "1", invoice_id: 13, job_id: 1, client_id: 6, notes: "111111", date_received: "2014-03-17", number: "1111", created_at: "2014-03-18 03:42:33", updated_at: "2014-03-18 03:42:33", order_id: nil>

Payment.find(58).invoice
  Payment Load (1.0ms)  SELECT "payments".* FROM "payments" WHERE "payments"."id" = $1 LIMIT 1  [["id", 58]]
 => true

似乎SQL查询构造不正确。

模型关联

class Payment < ActiveRecord::Base
  belongs_to :invoice
end
class Invoice < ActiveRecord::Base
  has_many :payments
end

1 个答案:

答案 0 :(得分:0)

正在运行付款模型中定义的旧方法,而不是belongs_to,has_many关系方法。

删除以下代码解决了这个问题。

def invoice
  if self.invoice_id
    return true
  end
end