加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 5活动记录记录无效错误

发布时间:2020-12-17 03:42:54 所属栏目:百科 来源:网络整理
导读:我有两个Rails模型,即Invoice和Invoice_details. Invoice_details属于Invoice,Invoice有许多Invoice_details. 我无法使用Invoice中的accepts_nested_attributes_for通过Invoice模型保存Invoice_details. 我收到以下错误: (0.2ms) BEGIN(0.2ms) ROLLBACKComp
我有两个Rails模型,即Invoice和Invoice_details.
Invoice_details属于Invoice,Invoice有许多Invoice_details.
我无法使用Invoice中的accepts_nested_attributes_for通过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

控制器代码:

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|

解决方法

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

该错误是由于您在为发票保存invoice_detail时不允许invoice_id

在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_params的invoice_details_attributes中的invoice_id允许

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

要么

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读