【发布时间】:2016-06-26 16:01:54
【问题描述】:
我正在尝试更新数据库中保存的数组,但是更新操作不起作用。数组没有更新,也没有显示错误。表格中的其他参数在数据库中正确更新。
表单发送一个数组作为参数之一(在本例中为responses: []):
"task"=> {"title"=>"tasko uno", "responses"=>["yes", "no", "maybe", "other"] ... }
更新动作:
def update
@task = Task.find(params[:id])
if @task.update(tasks_params)
redirect_to edit_task_path
else
render 'new'
end
end
参数权限:
private
def tasks_params
params.require(:task).permit(:title, :help, :task_type, :taskflow_id, :responses => [])
end
数据库是开箱即用的sql-lite,任务模型有serialize :responses, Array,数组列的类型为text,列标题为responses。
任何帮助将不胜感激。
编辑 迁移文件:
class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.string :title
t.integer :task_type
t.text :help
t.text :responses
t.belongs_to :taskflow
t.timestamps null: false
end
end
end
更新动作服务器日志:
Started PATCH "/tasks/1" for 127.0.0.1 at 2016-06-28 12:37:12 +0100
Processing by TasksController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"BL2fI3JDIGfTqWxQHInR/NFI6N/agETaUb97lAZ86PpNmpj1ofQ+TRkHZNdiISyOMlag3geleig6PsaqaWNr8Q==", "task"=>{"title"=>"tasko uno", "help"=>"some help text", "task_type"=>"2", "taskflow_id"=>"1"}, "responses"=>["test1", "test2"], "commit"=>"Update Task", "id"=>"1"}
Task Load (0.1ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT 1 [["id", 1]]
(0.0ms) begin transaction
(0.0ms) commit transaction
Taskflow Load (0.1ms) SELECT "taskflows".* FROM "taskflows" WHERE "taskflows"."id" = ? LIMIT 1 [["id", 1]]
Redirected to http://localhost:3000/taskflows/1/edit
Completed 302 Found in 3ms (ActiveRecord: 0.2ms)
表单 - 我正在尝试创建一个动态添加字段的表单:
<%= bootstrap_form_for @task do |f| %>
<%= f.text_field :title %>
<%= f.text_area :help %>
<%= f.text_field :task_type %>
<%= f.hidden_field :taskflow_id, value: @taskflow.id %>
<hr>
<p><strong>Responses</strong></p>
<div class="admin-task-responses">
<% if @task.responses %>
<% @task.responses.each do |r| %>
<%= render "tasks/task_response", {:res => r} %>
<% end %>
<% end %>
</div>
<div class="btn btn-primary add-response-btn">
<span class="glyphicon glyphicon-plus"></span> Add Response
</div>
<%= f.submit %>
<% end %>
部分:
<% if local_assigns.has_key? :res %>
<div class="task-response form-group">
<%= text_field_tag "responses[]", '', :class => 'form-control', :value => res %>
</div>
<% end %>
【问题讨论】:
-
@gen 谢谢,但我已经尝试过了 - 我在模型中使用
serialize :responses并检查了responses是复数形式。它没有抛出错误,所以我很难找到正在发生的事情。 -
请添加您的服务器日志以进行更新操作。你知道怎么用撬吗?您应该在更新后检查您的对象。
-
同时发布你的迁移,并尝试在没有 tasks_params 方法的情况下传递参数。
-
@gen 谢谢,我已经添加了迁移文件和更新操作的日志。在没有 task_params 的情况下传递参数会引发禁止属性错误。我会试一试。
标签: ruby-on-rails database activerecord