Adding fields and keep only one form, one submit button:
= form_tag(url: create_user_path, remote: true) do
%table
%tr
%td= text_field_tag 'user[][first_name]'
%td= text_field_tag 'user[][last_name]'
%tr.actions
%td= submit_tag 'Save'
%td= button_tag 'Add new user form', id: 'add_user_form'
%tr.new_user_row.hidden # hidden class matches the css rule: {display:none;}
%td= text_field_tag "user[][first_name]"
%td= text_field_tag "user[][last_name]"
:javascript # jQuery
$('#add_user_form').bind('click', function(e) {
var row = $('tr.new_user_row').clone().removeClass('hidden new_user_row');
$('tr.actions').before(row); # will append the <tr> before the actions
});
In UsersController:
def create
params[:user].each do |attr|
User.create(attr)
end
end
The row tr.new_user_row.hidden
serves the purpose of template for a new line: by clicking on the button #add_user_form
, the JS code will select the template row, clone
it and add this new row with empty inputs as the last visible row of the table.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…