I have two models namely Invoice and InvoiceDetails and:
class Invoice < ActiveRecord::Base
has_many :invoice_details
Now an User has the ability to edit an invoice, so he can remove the invoiceDetails attributes from the invoice.
So how can I delete those nested attributes of the invoiceDetails model while updating the invoice(parent) model.
I'm using AngularJS for client side.
The Update Action :
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
The Invoice Model
class Invoice < ApplicationRecord
has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy
belongs_to :customer
accepts_nested_attributes_for :invoiceDetails
end
The InvoiceDetails Model
class InvoiceDetail < ApplicationRecord
belongs_to :invoice
belongs_to :product
end