在rails上的ruby中的after_save错误

时间:2012-08-10 04:02:39

标签: ruby-on-rails ruby-on-rails-3 activerecord model

我有两个相互链接的模型,我正在尝试做一个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

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

未存储值。什么似乎是问题?对此事的指导将有所帮助。

提前致谢。 :)

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您未在customer_bill_id中设置create,将create更改为build,如下所示:

customer_ledger.build(:date => self.date, :customer_id => self.customer_id, :user_id => self.user_id)

答案 2 :(得分: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