【问题标题】:Rails - How to delete associated attributes while updating a parent?Rails - 如何在更新父级时删除关联的属性?
【发布时间】:2017-07-08 10:39:13
【问题描述】:

我有两个模型,即InvoiceInvoiceDetails 和:

class Invoice < ActiveRecord::Base

  has_many :invoice_details

现在用户可以编辑发票,因此他可以删除 invoice 中的 invoiceDetails 属性。 那么如何在更新invoice(parent) 模型的同时删除 invoiceDetails 模型的那些嵌套属性

我在客户端使用 AngularJS。

更新操作:

  def update
    invoice_id = params[:id]
    invoice = Invoice.find(invoice_id)
    if invoice.update(invoice_params)
      render json: invoice, status: 200
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def invoice_params
    invoice_params = params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, :totalTax, :totalDiscount, :bill_date,:company_id, { invoice_details: [:id,:invoice_id,:product_id,:quantity, :discount, :subtotal, :tax] })
    invoice_params[:invoiceDetails_attributes] = invoice_params.delete :invoice_details
    invoice_params.permit!
  end

发票模型

class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails
end

InvoiceDetails 模型

class InvoiceDetail < ApplicationRecord
  belongs_to :invoice
  belongs_to :product
end

【问题讨论】:

  • 您需要为每个 InvoiceDetail 对象传递 _destroy 参数 true 或 false。
  • 能否请您举例说明答案

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


【解决方案1】:

如果有人在这方面停滞不前,这就是我所做的。我在 InvoiceDetails(child) 模型中添加了一个属性 is_hide。 当用户删除 InvoiceDetails 属性时,is_hide 属性设置为 true

Invoice(父)模型中,我使用了 before_save 回调并遍历 InvoiceDetails 属性并调用 ma​​rk_for_destruction 其中is_hide = true

这就是我的 Invoice 模型的外观:

class Invoice < ApplicationRecord
  has_many :invoiceDetails, inverse_of: :invoice, dependent: :destroy, autosave: true
  belongs_to :customer
  accepts_nested_attributes_for :invoiceDetails

  before_save :mark_children_for_removal

  def mark_children_for_removal
    invoiceDetails.each do |child|
      child.mark_for_destruction if child.is_hide?
    end
  end

end

【讨论】:

    【解决方案2】:

    现在(不确定从什么时候开始)这个功能已经内置,你可以使用_destroy 属性。确保在您的参数中允许它,并且只需在嵌套表单中添加一个复选框:

    <%= nested_form.check_box '_destroy' %>
    

    这将在更新/保存时删除所有标记的项目。

    另请参阅此答案:https://stackoverflow.com/a/7151191/1595029

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多