我在使用导轨项目invoice
更新accepts_nested_attributes_for
的嵌套属性时遇到问题:
当我为每个项目选择数量时,它们都保存与第一个项目的值相同,例如:
在发票的表格中,我有3个不同的项目,每个项目有3个不同的数量。无论我为每个值选择什么值,记录总是与第一个项目的值一起保存。
这是控制器:
def edit
@invoice = Invoice.find(params[:id])
@printers = Printer.cheap_first
(9-@invoice.invoice_items.size).times do
@invoice.invoice_items.build
end
end
def update
@invoice = Invoice.find(params[:id])
if @invoice.update(invoice_params)
flash[:notice] = "Invoice updated succesfully."
redirect_to(:action =>'show')
else
render('edit')
end
end
private
def invoice_params
params.require(:invoice).permit(:client, :salesman, :discount, :organization, :address, :zp, :currency, :rate, invoice_items_attributes: [:id, :quantity, :printer_id, :_destroy])
end
以下是模型:
class Invoice < ActiveRecord::Base
has_many :invoice_items, dependent: :destroy
has_many :printers, :through => :invoice_items
accepts_nested_attributes_for :invoice_items, reject_if: proc {|attributes| attributes['printer_id'].blank?}, allow_destroy: true
end
以下是视图:
<% z = 0 %>
<%= f.fields_for :invoice_items, remote: true do |ff| %>
<div id=<%="invoice_item_#{z}"%> class="hidden" >
<div class="col-md-4 col-sm-6 col-xs-12">
<h3><%="Printer #{z+1}"%></h3>
<div class="form-group form-horizontal">
<%= ff.label(:printer_id, "Printer:") %>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-cube fa-lg" aria-hidden="true"></i>
</div>
<%= ff.select(:printer_id, @printers.map { |s| [s.name, s.id] }, {:include_blank => 'Select a printer'},{:class => 'form-control'}) %>
</div>
<%= ff.label(:quantity, "Quantity:") %>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-shopping-cart fa-lg" aria-hidden="true"></i>
</div>
<%= ff.select(:quantity, options_for_select(1..10),{}, {:class => 'form-control', :placeholder => 'Number'}) %>
</div>
</div>
</div>
</div>
<% z = z+1 %>
<% end %>
在更新发票时,代码有什么问题或我在:quantity
中实现更改所缺少的内容?