Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

ruby on rails - Multiple non-nested model creation on same page

Is there a way to create multiple model on the same page that are not nested inside another?

For instance, I would like to have a form where you can create users. It has two simple fields, firstname and last name, displayed on the same line. I would like to be able to add a link "Add a new user" which would create (using javascript) an identical line without post-back and allow me to create two users on the same page submit.

How can I achieve that using rails?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...