gpt4 book ai didi

ruby-on-rails - Rails 5 Active Record 记录无效错误

转载 作者:数据小太阳 更新时间:2023-10-29 07:13:20 26 4
gpt4 key购买 nike

我有两个 Rails 模型,即 InvoiceInvoice_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 的代码片段:

class Invoice < ApplicationRecord
has_many :invoice_details
accepts_nested_attributes_for :invoice_details
end

invoice_details.rb 的代码片段:

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

传递给 Controller ​​的原始 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|

最佳答案

ActiveRecord::RecordInvalid (Validation failed: Invoice details invoice must exist):

错误是由于您不允许invoice_id同时为invoice保存invoice_detail

Rails 5 中,默认情况下会验证关联对象的存在。您可以通过设置 optional :true

来绕过此验证

来自Guides

If you set the :optional option to true, then the presence of the associated object won't be validated. By default, this option is set to false.

解决方案:

invoice_paramsinvoice_details_attributes 中允许 invoice_id

def invoice_params
params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, invoice_details_attributes: [:product_id, :invoice_id])
end

如果你不想,那么设置optional :true

class InvoiceDetail < ApplicationRecord
belongs_to :invoice, optional :true
end

关于ruby-on-rails - Rails 5 Active Record 记录无效错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44605029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com