Rails 5活动记录记录无效错误

时间:2017-06-17 13:11:11

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-5

我有两个Rails模型,即发票 Invoice_details Invoice_details属于 发票发票包含许多Invoice_details。 我无法使用 Accept_nested_attributes_for in 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

传递给控制器​​的原始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|

2 个答案:

答案 0 :(得分:6)

  

ActiveRecord :: RecordInvalid(验证失败:发票详细信息   发票必须存在):

错误是由于您在invoice_id

保存invoice_detail不允许 invoice

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

来绕过此验证

来自Guides

  

如果将:optional选项设置为true,则表示存在   相关对象无法验证。默认情况下,此选项已设置   为假。

<强> 解决方案:

invoice_id invoice_details_attributes

中的invoice_params允许def invoice_params params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, invoice_details_attributes: [:product_id, :invoice_id]) end
optional :true

OR

如果您不愿意,请设置class InvoiceDetail < ApplicationRecord belongs_to :invoice, optional :true end

<?php
$url = 'http://server.com/image.psd';
$data = json_decode(file_get_contents('http://api.rest7.com/v1/image_convert.php?url=' . $url . '&format=png'));

if (@$data->success !== 1)
{
    die('Failed');
}
$image = file_get_contents($data->file);
file_put_contents('rendered_page.png', $image);

答案 1 :(得分:2)

当我通过使用明确声明两个模型之间的双向关系时,我仍然不知道上述事情无效的原因inverse_of

class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice
  accepts_nested_attributes_for :invoiceDetails
end

Rails 似乎没有在 invoice_details 上设置发票属性,然后尝试保存它,触发验证错误。这有点令人惊讶,因为其他 has_many 关系应该具有相同的保存机制并且工作得很好。

经过一段谷歌搜索后,我发现在旧版本的Rails中发生这种行为的帖子很少,我不知道新版本中是否仍然存在。 可以在以下链接中查看:

  1. https://github.com/rails/rails/issues/6161#issuecomment-8615049
  2. https://github.com/rails/rails/pull/7661#issuecomment-8614206
  3. https://github.com/rails/rails/issues/6161#issuecomment-6330795