2015-09-10 49 views
0

這是我的問題。 (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在提交結果。 我測試了多件事,但仍然陷在同樣的問題。

感謝您的幫助!

+0

嘗試添加'index'選項的'fields_for'方法,'= f.fields_for f.object.purchase_items。 build,index:index do | p | ...' –

+0

完美!那項工作,非常感謝,作爲額外的答案,你能解釋一下,把索引放在那裏有什麼區別? 還是非常感謝的地段 – Thounder

回答

1

要使用陣列狀參數添加index選項給fields_for方法:

= f.fields_for f.object.purchase_items.build, index: index do |p| 
    # some code here 

我是同樣的問題,忘記其中我發現這個棘手選項。

enter image description here

快樂編碼!

+0

這很好,謝謝! – Thounder

+0

最後一個想法,即使我現在已經購買了所有商品,哈希值爲「purchase」=> {「purchase_item」=>而不是「purchase」=> {「purchase_items」=> – Thounder

+0

您可以嘗試其他選項'fields_for'方法中的'name:'purchase_items''。讓我知道它是否有效。 –

0
Started POST "/purchases" for 127.0.0.1 at 2015-09-11 11:01:15 +0200 
Processing by PurchasesController#create as HTML 
Parameters: {"utf8"=>"✓", "authenticity_token"=>"yAsIoQPO2qEP+BBPA5UOvjUOM9b4Yh6b8bXy4H71P+c=", "purchase"=>{"type_of"=>"2", "purchase_item"=>[{"item_id"=>"378", "amount"=>"0", "comment"=>""}, {"item_id"=>"184", "amount"=>"0", "comment"=>""}, {"item_id"=>"188", "amount"=>"0", "comment"=>""}, {"item_id"=>"201", "amount"=>"0", "comment"=>""}, {"item_id"=>"199", "amount"=>"0", "comment"=>""}, {"item_id"=>"185", "amount"=>"0", "comment"=>""}, {"item_id"=>"186", "amount"=>"0", "comment"=>""}, {"item_id"=>"193", "amount"=>"0", "comment"=>""}, {"item_id"=>"182", "amount"=>"0", "comment"=>""}, {"item_id"=>"19", "amount"=>"0", "comment"=>""}, {"item_id"=>"196", "amount"=>"2", "comment"=>""}, {"item_id"=>"195", "amount"=>"0", "comment"=>""}, {"item_id"=>"197", "amount"=>"0", "comment"=>""}, {"item_id"=>"191", "amount"=>"0", "comment"=>""}, {"item_id"=>"190", "amount"=>"0", "comment"=>""}]}, "commit"=>"Commander"} 
Unpermitted parameters: purchase_item 

日誌clearely表明purchase_item不授權,這應該是的has_many