【问题标题】:How to dynamically add a (HABTM) collection_select + associated text_field in a Rails form?如何在 Rails 表单中动态添加(HABTM)collection_select + 关联的 text_field?
【发布时间】:2014-04-28 18:18:26
【问题描述】:

对于 Rails 中的个人发票应用程序,我可以使用以下建议:在新发票表单中,如何通过单击动态添加一个新行,该行由 products 的 collection_select 和 amount 的关联 text_field 组成add new product?

由于一张发票有很多产品,而一个产品有很多发票,我认为这是一种双向的 HABTM 关系。因此我创建了表invoicesproducts,以及它们的连接表invoices_products

我希望invoices/new 页面有一个表单,用户可以在其中使用 collection_select 选择产品(所有产品都已预加载在 products 表中)并在其后面的文本字段中填写金额. 用户应该能够通过单击add new product 来复制这两个字段(collection_select 和 text_field),类似于RailsCast #403 Dynamic Forms 04:50

现在我该怎么做呢?我应该将amount text_field 中的数据放在哪个表中,因为每张发票有多个产品,所以有多个金额?

任何正确方向的答案将不胜感激!

【问题讨论】:

    标签: ruby-on-rails forms dynamic has-and-belongs-to-many collection-select


    【解决方案1】:

    这取决于你想要多少额外的字段

    可以找到一个很好的教程here


    Ajax

    正确的方法是使用 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 %>
    

    【讨论】:

    • 感谢里奇!我对 Ajax 还不太了解,但我会去看看!
    猜你喜欢
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 2016-09-06
    • 2011-03-21
    • 1970-01-01
    相关资源
    最近更新 更多