2

我有两个相互链接的模型,我正在尝试进行 after_save,在模型中创建,代码如下。

class CustomerBill < ActiveRecord::Base
  after_save :updating_and_creating_ledger_items
  has_many :customer_ledgers, :dependent => :destroy

  def updating_and_creating_ledger_items
    CustomerLedger.create(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
  end
end

客户账本模型

class CustomerLedger < ActiveRecord::Base
  belongs_to :customer_bill,  :foreign_key => "customer_bill_id"
end

现在的问题是程序执行完美,但值没有放入数据库中。如果我检查客户分类帐,它仍然是空的。

这些值没有被存储。似乎是什么问题?对此事的指导会有所帮助。

提前致谢。:)

4

3 回答 3

2

添加

  validates_associated :customer_ledgers

在 customer_bill.rb 中

尝试

ledger = customer_ledgers.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
ledger.save

编辑以避免验证,使用

ledger = customer_ledgers.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
ledger.save(:validate => false)
于 2012-08-10T04:41:02.200 回答
0

CustomerLedger可能未通过验证检查。代替:

def updating_and_creating_ledger_items
  CustomerLedger.create(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
end

和:

def updating_and_creating_ledger_items
  ledger = customer_ledgers.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
  ledger.save(:validate => false)
end
于 2012-08-10T14:19:47.653 回答
0

您没有将 ,customer_bill_id中的设置create更改createbuild

customer_ledger.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)
于 2012-08-10T04:13:41.217 回答