Rails - 如何在更新父级时删除关联的属性?

时间:2017-07-08 10:39:14

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

我有两个模型,即InvoiceInvoiceDetails以及:

class Invoice < ActiveRecord::Base

  has_many :invoice_details

现在用户能够编辑 发票,这样他就可以删除 来自发票的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

2 个答案:

答案 0 :(得分:0)

如果有人因此而停滞不前,这就是我的所作所为。我在 InvoiceDetails (子)模型中添加了 is_hide 属性。 当用户删除 InvoiceDetails 属性时, is_hide 属性设置为 true

Invoice (父级)模型中,我使用 before_save 回调并迭代 InvoiceDetails 属性并调用 mark_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

答案 1 :(得分:0)

现在(不确定实际何时),此功能已内置,您可以只使用_destroy属性。确保在您的参数中允许它,然后在嵌套表单中添加一个复选框:

<%= nested_form.check_box '_destroy' %>

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

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