2015-07-21 37 views
3

我有三個模型需要一起工作 - product,line_productorder,其中line_product鏡像productorder。因此,它看起來像這樣:如何用Rails在一個表單中添加多個單名元素?

product.rb

has_many :line_products 

order.rb

has_many :line_products 

line_product.rb

belongs_to :order 
belongs_to :product 

我想製作一份表單,其中每個產品的旁邊都有一個輸入字段,用戶可以爲任何產品輸入任意數量(計數),單擊提交,並且計數大於0的所有產品他們的形式,將變爲line_productsorder其中order.id: 1(例如)。截至目前,只有最後一個產品被添加到訂單中。

我該怎麼做?

編輯

的形式看起來像這樣:

= form_for @line_product do |lp| 
    = lp.hidden_field :order_id, value: Order.last.id 
    %section#product_list 
    - if notice 
     %section.notice=notice 
    %ul#products 
     [email protected] do |p| 
     %li.product_list 
      %article.product 
      %section.product_left 
       = image_tag p.image.url(:medium) 
       %div.clear 
       %span.price= number_to_currency(p.price,:unit=>'€ ') 

      %section.product_right 
       %section.product_about 
       %span.title= p.title 
       %span.description= p.description 
       %span.description.desceng= p.description_eng 
       = lp.hidden_field :product_id, value: p.id 

       %section.product_order 
       = lp.number_field(:count, min: '0', value: '', class: 'product_count') 


    %section#order_accepting 
    = lp.submit "Add to cart", class:'add_to_cart' 

回答

0

有相當多的方式,你可以處理這個問題,例如,你可以去下使用accepts_nested_attributes這是生成創建/編輯多個對象形式的一個非常通用的方式途徑然後處理這些數據。

一種用於這種特定情況下稍微簡單替代方案將是產生針對每個產品(而不是一對你有隱藏的輸入和數字輸入的)

number_field_tag "count[#{product.id}]" 

單個數字輸入這將導致params[:count]感形式

{ "1" => 23, "2" => "", "3"=> "1"} 

假設你有3個產品,IDS 1,2,3和你已經進入23的最後的第一數量和1的哈希值。

然後,您需要一些控制器代碼來遍歷此散列並生成相應的line_product對象

相關問題