gpt4 book ai didi

javascript - Rails 将动态字段插入数据库

转载 作者:行者123 更新时间:2023-11-28 09:00:12 24 4
gpt4 key购买 nike

我有一个简单的应用程序,具有单个模型(任务)和单个属性(名称)。

app/views/tasks/_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"%>

应用程序/ Assets /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)

我想要为我输入的每个名称分配一个单独的任务/名称。

最佳答案

在 Rails 4 中,强参数功能要求您将 Controller 内的参数列入白名单。另外,根据答案here ,如果不进一步调整,参数数组就无法列入白名单,因此您需要

params.require(:task).permit(name: [])

关于javascript - Rails 将动态字段插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17861904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com