簡體   English   中英

如何在Rails表單中動態添加(HABTM)collection_select +關聯的text_field?

[英]How to dynamically add a (HABTM) collection_select + associated text_field in a Rails form?

對於Rails中的個人開票應用程序,我可以使用以下建議:在新的發票表單中,如何通過單擊“ add new product ”來動態添加新行,該行包括products的collection_select和amount的關聯text_field?

由於一個發票有很多產品,而一個產品有很多發票,所以我認為這是兩種方式的HABTM關系。 因此,我創建了表invoicesproducts及其聯接表invoices_products

我希望invoices/new頁面具有一種表單,用戶可以使用collection_select來選擇產品(所有產品都已預裝在products表中)並在其后面的文本字段中填寫金額。 用戶應該能夠通過單擊add new product (例如RailsCast #403 Dynamic Forms 04:50 )來復制這兩個字段(collection_select和text_field)。

現在我該怎么做呢? 而且由於每張發票中有多個產品,所以我會將來自amount text_field的數據放在哪個表中,因此金額又多少呢?

任何正確方向的回答將不勝感激!

這取決於您想要多少個其他字段

一個很好的教程可以在這里找到


阿賈克斯

正確的方法是使用Ajax動態添加元素

這很棘手,因為這意味着您不會為動態添加的項目提供form_builder對象。 無論如何,您仍然可以使用以下代碼進行操作:

#config/routes.rb
get "new_field_path", to: "invoices#new_item"

#app/views/controller/index.html.erb
<%= ... form %>
<%= link_to "Add Field", new_field_path, remote: :true %>

調節器

#app/controllers/invoices_controller.rb
def new_item
   @invoice = Invoice.new
   @invoice.products.build
   render "new_item", layout: false
end

#app/views/invoices/new_item.html.erb
<%= form_for @invoice do |f| %>
    <%= render partial: "products_fields", locals: { f: f } %>
<% end %>

#app/views/invoices/_products_fields.html.erb
<%= f.fields_for :products, child_index: Time.now.to_i do |p| %>
    <%= p.text_field :name %>
<% end %>

形成

#app/views/invoices/new.html.erb
<%= form_for @invoice do |f| %>
   <%= render partial: "products_fields", locals: { f: f } %>
   <%= link_to "Add Field", new_field_path, remote: :true %>
   <%= f.submit %>
<% end %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM