我有一个简单的应用程序,只有一个模型(任务)和一个属性(名称)。
<%= 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"%>
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)
我想为我输入的每个名字分别设置一个任务/名称。
答案 0 :(得分:0)
在Rails 4中,强参数功能要求您将控制器内的参数列入白名单。此外,根据答案here,如果没有进一步调整,一系列参数不能列入白名单,因此您需要
params.require(:task).permit(name: [])