发票有许多发票条目:
class Invoice < ActiveRecord::Base
has_many :invoice_entries, :autosave => true, :dependent => :destroy
validates_presence_of :date
end
class InvoiceEntry < ActiveRecord::Base
belongs_to :invoice
validates_presence_of :description
end
假设我们在数据库中有一张发票:
id: 1
date: '2013-06-16'
它有两个发票条目:
id: 10 id: 11
invoice_id: 1 invoice_id: 1
description: 'do A' description: 'do C'
现在,我有了新的发票条目:
id: 10
description: 'do B' description: 'do D'
(Existing invoice entry (New invoice entry
with updated description) without id)
我希望发票只有这些新的发票条目(这意味着id=11
应该删除发票条目)。
invoice.invoice_entries = new_invoice_entries
似乎做了一半的工作。它使用 删除发票条目id=11
,使用 description 创建新发票条目'Do D'
,但不会使用id=10
from 'Do A'
to'Do B'
更新发票条目的描述。我猜当 Rails 看到一个存在id
的 in 时new_invoice_entries
,它会完全忽略它。真的吗?如果是,这背后的理由是什么?
我的完整代码如下。你会如何解决这个问题?(我使用 Rails 4,以防它简化代码。)
# PATCH/PUT /api/invoices/5
def update
@invoice = Invoice.find(params[:id])
errors = []
# Invoice entries
invoice_entries_params = params[:invoice_entries] || []
invoice_entries = []
for invoice_entry_params in invoice_entries_params
if invoice_entry_params[:id].nil?
invoice_entry = InvoiceEntry.new(invoice_entry_params)
errors << invoice_entry.errors.messages.values if not invoice_entry.valid?
else
invoice_entry = InvoiceEntry.find_by_id(invoice_entry_params[:id])
if invoice_entry.nil?
errors << "Couldn't find invoice entry with id = #{invoice_entry_params[:id]}"
else
invoice_entry.assign_attributes(invoice_entry_params)
errors << invoice_entry.errors.messages.values if not invoice_entry.valid?
end
end
invoice_entries << invoice_entry
end
# Invoice
@invoice.assign_attributes(date: params[:date])
errors << @invoice.errors.messages.values if not @invoice.valid?
if errors.empty?
# Save everything
@invoice.invoice_entries = invoice_entries
@invoice.save
head :no_content
else
render json: errors.flatten, status: :unprocessable_entity
end
end