lakoz lakoz - 1 year ago 93
Ruby Question

Ruby on Rails - Create a form with Multiple instances of the same model

I have a model, namely "bank_accounts", which contains many users

I want to use a form to list out all users (while the first name is editable), so that one click of "submit" can gather all users' first name.

-@bank_accounts.each do |account|
=form_for account do |f|
=f.text_field :first_name

The code above gives something like

<form class="edit_bank_accounts" id="edit_bank_account_1" action="/bank_account/1" accept-charset="UTF-8" method="post">
<input type="text" value="123" name="bank_account[first_name]" id="bank_account_first_name"/>
<form class="edit_bank_accounts" id="edit_bank_account_2" action="/bank_account/2" accept-charset="UTF-8" method="post">
<input type="text" value="456" name="bank_account[first_name]" id="bank_account_first_name"/>

But what I want is

<form class="edit_bank_accounts" id="edit_bank_account" action="/bank_account" accept-charset="UTF-8" method="post">
<input type="text" value="123" name="bank_account[1][first_name]" id="bank_account_first_name"/>
<input type="text" value="456" name="bank_account[2][first_name]" id="bank_account_first_name"/>

How to generate
for the form in Ruby on Rails?


Answer Source

Move the loop inside your form tag

= form_tag '/bank_account', html: { id: 'edit_bank_accounts', class: 'edit_bank_accounts' } do
  -@bank_accounts.each do |account|
    = text_field_tag :bank_account_first_name, account.first_name, name: "bank_account[#{}][first_name]"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download