ruby-on-rails – 如何拦截accepts_nested_attributes_for?
我有一个Rails应用程序,有两个模型:SalesTransactions和PurchaSEOrders.
在PurchaSEOrders模型中,使用“purchase_order_number”作为关键字段注册新条目.我使用模型的create方法来搜索先前是否已经注册了“purchase_order_number”,如果是,则重用该记录并在SalesTransaction记录中使用其id.如果该名称尚未注册,我继续执行创建,然后在SalesTransaction中使用新的PurchaSEOrder记录ID(链接到关联PO的foreign_id). 请注意,在我在create方法中查找之前,我没有现有的PurchaSEOrder记录ID(所以这不是’如何使用’accepts_nested_attributes_for’更新记录?’的问题,我可以做一旦我有了id). 在某些情况下,我的应用程序会记录一个新的SalesTransaction,并同时创建一个新的PurchaSEOrder.它使用accepts_nested_attributes_for来创建PurchaSEOrder记录. 问题似乎是当使用’accepts_nested_attributes_for’时,不会调用create,因此我的模型没有机会拦截创建,并查看’purchase_order_number’是否已经注册并处理该情况. 我很欣赏有关如何拦截’accepts_nested_attributes_for’创建以允许一些预处理的建议(即查看具有该数字的PurchaSEOrder记录是否已经存在,如果存在,则使用它). 并非所有Sales都有PurchaSEOrder,因此PurchaseTransaction中的PurchaSEOrder记录是可选的. (我已经看到了一个涉及:reject_if的kludge,但是这不允许我将现有的记录id添加为父记录中的foreign_id.) 谢谢. 解决方法
您可以使用验证并保存回调来执行您需要的操作.
假设设置: class SalesTransaction < ActiveRecord::Base belongs_to :purchase_order,:foreign_key => "po_purchase_order_no",:primary_key => "purchase_order_no" accepts_nested_attributes_for :purchase_order end class PurchaSEOrder < ActiveRecord::Base has_many :sales_transactions,:primary_key => "purchase_order_no" before_validation :check_for_exisitng_po # maybe only on create? accepts_nested_attributes_for :sales_transactions private def check_for_exisitng_po existing_po = PurchaSEOrder.find_by_purchase_order_no(self.purchase_order_no) if existing_po self.id = existing_po.id self.reload # don't like this,also will overwrite incoming attrs @new_record = false # tell AR this is not a new record end true end end 这应该再次完全使用accepts_nested_attributes_for. gist w /测试 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |