使用.create在模型中创建关联记录失败,没有nil错误的方法

时间:2013-09-11 12:41:34

标签: ruby-on-rails activerecord ruby-on-rails-4

所以我真的很难做到这一点......基本上我想做的是保存或创建过程记录时我想检查状态是否设置为已完成。然后,如果是,那么继续创建一个关联的交易记录,其中包含过程记录中的详细信息。 但是我继续为nil获得*** NoMethodError Exception: undefined method create':NilClass“`

只是不确定去哪里!!

class Procedure < ActiveRecord::Base
store_accessor :properties, :tooth, :buccal, :mesial, :occlusal, :distal, :lingual

belongs_to :item
belongs_to :patient
belongs_to :practice
belongs_to :provider
belongs_to :operatory
belongs_to :appointment 
belongs_to :transaction

before_create :create_transaction
before_save :create_transaction
before_save :check_if_was_marked_as_complete

validates :item, :patient, :provider, :date, presence: true
validates_associated :item, :patient,  :provider


private

def create_transaction
      if status == "completed"
        transaction.create do |t|
          t.amount = fee
          #t.practice = self.practice
          t.debit_account = patient.family.account
          t.credit_account = provider.revenue_account
          #t.patient = self.patient
         end
   end
end

def check_if_was_marked_as_complete
    if self.status_was == "completed"
        return false
    else
        return true
    end     
end
end

编辑 * 我的方法现在看起来像这样

def create_association
 if status == "completed"
  create_transaction do |t|
    t.amount = fee
    #t.practice = self.practice
    t.debit_account = patient.family.account
    t.credit_account = provider.revenue_account
    #t.patient = self.patient
  end
    end
end

1 个答案:

答案 0 :(得分:1)

您的交易是nil,直到它存在。所以procedure.transaction #=> nilnil.create #=> undefined method create for nil

要在belongs_to关联中构建关联对象,您可以使用以下方法:

  • build_association
  • create_association
  • create_association!

由关联对象替换(即build_transaction,create_transaction等)

您应该做的第一件事是重命名回调create_association,因为此方法仍由Rails定义。

然后在你的回调中:

create_transaction do |t|
  # ...
end
相关问题