How to dynamically add a (HABTM) collection_select + associated text_field in a Rails form? -
for personal invoicing app in rails use advice on following: in new invoice form, how dynamically add new row consisting of collection_select products
, associated text_field amount
clicking add new product
?
since 1 invoice has many products , product has many invoices, figured habtm relationship both ways. therefore have created tables invoices
, products
, , join table invoices_products
.
i invoices/new
page have form user can use collection_select pick product (all products preloaded in products
table) , fill in amount in text field behind it. user should able duplicate these 2 fields (collection_select , text_field) clicking add new product
, railscast #403 dynamic forms 04:50
.
now how go doing that? , in table put data amount
text_field, since there multiple products per invoice multiple amounts?
any answer in right direction appreciated!
this depends on how many additional fields want
a tutorial can found here
ajax
the right way add element dynamically ajax
this tricky because means you're not going have form_builder
object available dynamically added items. regardless, can still code:
#config/routes.rb "new_field_path", to: "invoices#new_item" #app/views/controller/index.html.erb <%= ... form %> <%= link_to "add field", new_field_path, remote: :true %>
controller
#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 |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 |p| %> <%= p.text_field :name %> <% end %>
form
#app/views/invoices/new.html.erb <%= form_for @invoice |f| %> <%= render partial: "products_fields", locals: { f: f } %> <%= link_to "add field", new_field_path, remote: :true %> <%= f.submit %> <% end %>
Comments
Post a Comment