2017-07-08 32 views
1

我有两个型号,即InvoiceInvoiceDetails和:Rails - 如何在更新父项时删除关联的属性?

class Invoice < ActiveRecord::Base 

    has_many :invoice_details 

现在的用户有能力编辑发票,这样他就可以删除invoiceDetails从属性发票。 那么我怎样才能删除那些嵌套属性的invoiceDetails模型,同时更新invoice(parent)模型。

我使用客户端AngularJS。

更新操作:

def update 
    invoice_id = params[:id] 
    invoice = Invoice.find(invoice_id) 
    if invoice.update(invoice_params) 
     render json: invoice, status: 200 
    else 
     render json: { errors: invoice.errors }, status: 422 
    end 
    end 

    def invoice_params 
    invoice_params = params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, :totalTax, :totalDiscount, :bill_date,:company_id, { invoice_details: [:id,:invoice_id,:product_id,:quantity, :discount, :subtotal, :tax] }) 
    invoice_params[:invoiceDetails_attributes] = invoice_params.delete :invoice_details 
    invoice_params.permit! 
    end 

发票型号

class Invoice < ApplicationRecord 
    has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy 
    belongs_to :customer 
    accepts_nested_attributes_for :invoiceDetails 
end 

InvoiceDetails模式

class InvoiceDetail < ApplicationRecord 
    belongs_to :invoice 
    belongs_to :product 
end 
+0

你需要传递_destroy参数真或假的每InvoiceDetail对象。 – Vishal

+0

请举例说明一下答案 – Paras

回答

0

万一有人停滞于此,这里是我做的。我在InvoiceDetails(子)模型添加is_hide属性。 当用户删除InvoiceDetails属性时,is_hide属性设置为true

发票(父)模型中,我使用before_save回调并通过InvoiceDetails迭代属性和称为mark_for_destruction其中is_hide =真

这是我的发票模型的外观:

class Invoice < ApplicationRecord 
    has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy, autosave: true 
    belongs_to :customer 
    accepts_nested_attributes_for :invoiceDetails 

    before_save :mark_children_for_removal 

    def mark_children_for_removal 
    invoiceDetails.each do |child| 
     child.mark_for_destruction if child.is_hide? 
    end 
    end 

end 
相关问题