【发布时间】:2017-04-03 15:47:09
【问题描述】:
尝试在 Rails 中使用 fields_for 时,我在控制台中收到这样的消息:
Parameters: .... "task"=>{"task_name"=>"111", "tag"=>{"tag_text"=>"222"}}, "commit"=>"Save"}
Unpermitted parameter: tag
我的带有 has_many 和 belongs_to 的模型:
class Task < ActiveRecord::Base
has_many :tags
accepts_nested_attributes_for :tags
end
class Tag < ActiveRecord::Base
belongs_to :task
end
新建/编辑页面的表单助手:
<%= form_for(@task) do |f| %>
<%= f.text_field :task_name %>
<%= f.fields_for([@task, @task.tags.build]) do |t| %>
<%= t.text_field :tag_text %>
<% end %>
<%= f.submit 'Save' %>
<% end %>
我的任务控制器(我使用脚手架生成它,并且大部分是默认的)
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
def index
@tasks = Task.all
end
def show
end
def new
@task = Task.new
@task.tags.build
end
def edit
@task.tags.build
end
def create
@task = Task.new(task_params)
respond_to do |format|
if @task.save
format.html { redirect_to @task, notice: 'Task was successfully created.' }
format.json { render :edit, status: :created, location: @task }
else
format.html { render :new }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to edit_task_path, notice: 'Task was successfully updated.' }
format.json { render :edit, status: :ok, location: @task }
else
format.html { render :edit }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
def destroy
@task.destroy
respond_to do |format|
format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
@task = Task.find(params[:id])
end
def task_params
params.require(:task).permit(:task_name, :task_sum, :status_id, :user_id, :target_release_id, tag_attributes: [:tag_text, :task_id])
end
end
【问题讨论】:
-
有一个标签参数被传递,你可以在这里看到它: - "tag"=>{"tag_text"=>"222"}}, - 但是你不允许 ":tag “在参数中。将 :tag 添加到参数中,它应该可以工作。
-
它没有帮助...也请在下面查看我对@ajeferson 回答的评论
标签: ruby-on-rails ruby