I have two Rails model namely Invoice and Invoice_details. An Invoice_details belongs to Invoice, and an Invoice has many Invoice_details. I'm not able to save Invoice_details via Invoice model using accepts_nested_attributes_for in Invoice.
I get the following error :
(0.2ms) BEGIN
(0.2ms) ROLLBACK
Completed 422 Unprocessable Entity in 25ms (ActiveRecord: 4.0ms)
ActiveRecord::RecordInvalid (Validation failed: Invoice details invoice must exist):
app/controllers/api/v1/invoices_controller.rb:17:in `create'
Below is the code snippet for invoice.rb
:
class Invoice < ApplicationRecord
has_many :invoice_details
accepts_nested_attributes_for :invoice_details
end
The code snippet for invoice_details.rb
:
class InvoiceDetail < ApplicationRecord
belongs_to :invoice
end
The Controller
code :
class Api::V1::InvoicesController < ApplicationController
respond_to :json
def index
comp_id = params[:comp_id]
if comp_id
invoices = Invoice.where(:company_id => comp_id)
render json: invoices, status: 201
else
render json: { errors: "Company ID is NULL" }, status: 422
end
end
def create
Rails.logger.debug invoice_params.inspect
invoice = Invoice.new(invoice_params)
if invoice.save!
render json: invoice, status: 201
else
render json: { errors: invoice.errors }, status: 422
end
end
def invoice_params
params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, invoice_details_attributes:[:product_id])
end
end
The raw JSON data passed to the controller :
{
"invoice":{
"total_amount":"100",
"balance_amount":"0",
"customer_id":"1",
"invoice_details_attributes":[{
"product_id":"4"
}]
}
}
invoice_details schema
|id | invoice_id | product_id | created_at | updated_at|
invoice schema
|id| total_amount |balance_amount | generation_date | created_at | updated_at | customers_id|
invoice_id
ininvoice_details_attributes
ofinvoice_params
– Anhydritebelongs_to
unless directed otherwise. – Soult