在同一页面上创建多个非嵌套模型 [英] Multiple non-nested model creation on same page

查看:55
本文介绍了在同一页面上创建多个非嵌套模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在同一页面上创建多个不嵌套在另一个页面中的模型?

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

例如,我想要一个表单,您可以在其中创建用户.它有两个简单的字段,名字和姓氏,显示在同一行上.我希望能够添加一个添加新用户"链接,该链接将创建(使用 javascript)一个相同的行而无需回发,并允许我在同一页面提交上创建两个用户.

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.

如何使用 Rails 实现这一目标?

How can I achieve that using rails?

推荐答案

添加字段,只保留一个表单,一个提交按钮:

= 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
  });

在用户控制器中:

def create
  params[:user].each do |attr|
    User.create(attr)
  end
end

<小时>

tr.new_user_row.hidden 用于新行的模板:通过点击按钮 #add_user_form,JS 代码将选择模板行, clone 它并添加这个带有空输入的新行作为表格的最后可见行.


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.

这篇关于在同一页面上创建多个非嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆