2016-07-22 63 views
0

練習中的邏輯是創建一個帳單,其中的帳單包含一定數量的產品清單。在視圖中選擇多個到多個模型的導軌

我今後3款:

  • 比爾
  • 產品
  • BillItem(這是比爾和產品之間的中間模式,爲多對多的關係)

模式更多清晰度:

create_table "bill_items", force: :cascade do |t| 
    t.integer "amount" 
    t.integer "product_id" 
    t.integer "bill_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.index ["bill_id"], name: "index_bill_items_on_bill_id" 
    t.index ["product_id"], name: "index_bill_items_on_product_id" 
end 

create_table "bills", force: :cascade do |t| 
    t.string "user_name" 
    t.string "dni" 
    t.date  "expiration" 
    t.float "sub_total" 
    t.float "grand_total" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

create_table "products", force: :cascade do |t| 
    t.string "name" 
    t.string "description" 
    t.float "price" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

首先,我有一個在我的數據庫中創建產品的列表。 對於我的BillController,我有一個_form.html.erb,我希望能夠爲選擇產品創建動態選擇並設置一個數量。

我的看法是下一個:

<%= form_for bill do |f| %> 
    <div> 
    <%= f.label :user_name %> 
    <%= f.text_field :user_name %> 
    </div> 

    <div> 
    <%= f.label :dni %> 
    <%= f.text_field :dni %> 
    </div> 

    <div> 
    <%= f.label :product %> 
    <%= f.collection_select :product_ids, Product.all, :id, :name %> 
    </div> 
    # Here i should add more selects if the user want to add more products. 

    <div><%= f.submit %></div> 
<% end %> 

我的問題還是我的問題是:如何「GROUPE」產品的識別碼與它們的數量。另一個問題是,我可以使用JS動態創建其他選擇?

回答

1

您需要將多個BillItem添加到您的表單以計算金額和產品。這是通過模型上的accepts_nested_attributes_for完成的。例如:

class Bill < ActiveRecord::Base 
    has_many :bill_items 
    accepts_nested_attributes_for :bill_items 
end 

在控制器中初始化Bill一個BillItem

class BillsController < ActionController::Base 
    def new 
    @bill = Bill.new 
    @bill.bill_items.build 
    end 
end 

然後在你的形式,使用fields_for幫助創建了子表單:

<%= form_for @bill do |f| %> 
    <div> 
    <%= f.label :user_name %> 
    <%= f.text_field :user_name %> 
    </div> 
    <div> 
    <%= f.label :dni %> 
    <%= f.text_field :dni %> 
    </div> 

    <%= f.fields_for :bill_items do |f| %> 
    <div> 
     <%= f.label :product %> 
     <%= f.collection_select :product_id, Product.all, :id, :name %> 
    </div> 
    <div> 
     <%= f.label :amount %> 
     <%= f.number_field :amount %> 
    </div> 
    <% end %> 
    <%= f.submit %></div> 
<% end %> 

而且是的,你可以use javascript to create new nested forms

+0

謝謝您花時間幫助我,您的回答是我需要的:) –