這是我的問題。 (Rails 4)窗體與multiples fields_for rails 4
我有一個購買,我希望能夠在一個表單中同時添加多個purchase_items。
class Purchase < ActiveRecord::Base
has_many :purchase_items, :dependent => :destroy
accepts_nested_attributes_for :purchase_items
class PurchasesController < ApplicationController
params.require(:purchase).permit(:purchase_items => [:item_id, :amount, :comment])
= form_for @purchase do |f|
%h2 Passer ma commande personnelle
%ul#ul-services
- @services.each_with_index do |service_item, index|
- index.even? ? float="float:left" : float="float:right"
%li.list-services{:style => float}
= f.fields_for @purchase.purchase_items.build, name: 'purchase_items', index: "" do |p|
= p.hidden_field :item_id, :value => service_item.id
= f.submit "Commander", :class => "btn btn-success add-to-cart" , :id => "add-to-cart"
其中@purchase是新購置的
當我提交表單,我總是有一個purchase_item
{"utf8"=>"✓",
"authenticity_token"=>"yAsIoQPO2qEP+BBPA5UOvjUOM9b4Yh6b8bXy4H71P+c=",
"purchase"=>{"purchase_item"=>{"item_id"=>"151",
"amount"=>"0",
"comment"=>""}},
"commit"=>"Commander"}
我無法弄清楚如何讓multile purchase_items在提交結果。 我測試了多件事,但仍然陷在同樣的問題。
感謝您的幫助!
嘗試添加'index'選項的'fields_for'方法,'= f.fields_for f.object.purchase_items。 build,index:index do | p | ...' –
完美!那項工作,非常感謝,作爲額外的答案,你能解釋一下,把索引放在那裏有什麼區別? 還是非常感謝的地段 – Thounder