我有一个带有单个模型(任务)和单个属性(名称)的简单应用程序。
应用程序/视图/任务/_form.html.erb
<%= form_tag :action => 'create' %>
<div id="dynamicInput">
Task Name <input type="text" name="task[name][]">
</div>
<input type="button" value="Add New Tag" onClick="addInput('dynamicInput');">
<%= submit_tag "Create"%>
应用程序/资产/javascripts/application.js
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "Task Name <input type='text' name='task[name][]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
上面的代码允许我添加任意数量的字段。我可以输入一个名称,但如果我动态添加 2 个字段,这就是我的参数的样子......
Started POST "/tasks" for 127.0.0.1 at 2013-07-25 12:36:57 -0400
Processing by TasksController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"PnTQnxM3GFRtqkXi09jLH8UJBiaRCI0chSZ716cVWJ0=", "task"=>{"name"=>["name1", "name2"]}, "commit"=>"Create"}
(0.1ms) begin transaction
SQL (5.6ms) INSERT INTO "tasks" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Thu, 25 Jul 2013 16:36:57 UTC +00:00], ["name", ["name1", "name2"]], ["updated_at", Thu, 25 Jul 2013 16:36:57 UTC +00:00]]
(153.1ms) commit transaction
Redirected to http://localhost:3000/tasks/1
Completed 302 Found in 165ms (ActiveRecord: 158.7ms)
我想为我输入的每个名称分别指定一个任务/名称。