【发布时间】:2013-03-02 05:35:40
【问题描述】:
理论:- 在customer bill 中创建记录后,我将发送两组数据和两个不同的模型。一组数据发送到ledger,一组数据发送到ledger_line_item。复杂性在于,在发送数据后,我希望将ledger_id 存储在ledger_line_item 中。代码如下
代码:-
class CustomerBill < ActiveRecord::Base
after_create :creating_ledger_line_items, :creating_ledger_items
def creating_ledger_items
CustomerLedger.create(:customer_id =>self.customer_id,/*rest of attributes*/)
end
def creating_ledger_line_items
CustomerLedgerLineItem.create(:customer_id =>self.customer_id,/*rest of attributes*/)
end
end
在我写的分类帐中
class CustomerLedger < ActiveRecord::Base
after_save :update_record_line_items
def update_record_line_items
a = CustomerLedgerLineItem.find_by_customer_id(self.customer_id)
a.update_attributes(:customer_ledger_id => self.id)
end
end
上面的代码工作正常,没有错误,但ledger_id 没有发布在ledger_line_items 中。我无法确定为什么会发生此错误?在创建账单后,我还有其他方法可以实现在ledger_line_items 中发布ledger_id 的目标吗?
需要指导。提前谢谢你。
【问题讨论】:
-
我看到的方式是您手动创建给定属性列表的项目。您可以通过查看
accepts_nested_attributes_for来实现您想要的,这将简化您的代码。
标签: ruby-on-rails activerecord callback ruby-on-rails-3.2 after-save