【发布时间】:2017-06-17 13:11:11
【问题描述】:
我有两个 Rails 模型,即 Invoice 和 Invoice_details。 一个Invoice_details属于属于Invoice,一个Invoice有很多Invoice_details。 我无法使用 accepts_nested_attributes_for in Invoice 通过 Invoice 模型保存 Invoice_details。
我收到以下错误:
(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'
下面是invoice.rb 的代码 sn-p :
class Invoice < ApplicationRecord
has_many :invoice_details
accepts_nested_attributes_for :invoice_details
end
invoice_details.rb 的代码 sn-p:
class InvoiceDetail < ApplicationRecord
belongs_to :invoice
end
Controller 代码:
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
传递给控制器的原始 JSON 数据:
{
"invoice":{
"total_amount":"100",
"balance_amount":"0",
"customer_id":"1",
"invoice_details_attributes":[{
"product_id":"4"
}]
}
}
invoice_details 架构
|id | invoice_id | product_id | created_at | updated_at|
发票架构
|id| total_amount |balance_amount | generation_date | created_at | updated_at | customers_id|
【问题讨论】:
-
尝试在
invoice_details_attributesofinvoice_params中添加invoice_id -
您可以发布发票详细信息的架构吗?那里的自动保存似乎出了点问题。
-
@Pavan 很好,我忘了 rails 5 现在验证
belongs_to,除非另有指示。 -
有效果吗?
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-5