强参数不允许参数通过?

时间:2014-06-28 18:28:22

标签: ruby-on-rails

这是我过去几天一直在努力解决的问题:

我有task和completed_task模型:

class Task < ActiveRecord::Base
  belongs_to :user
  has_many :completed_tasks   
end

class CompletedTask < ActiveRecord::Base
  belongs_to :task 
end  

我的表格上写着:

<% @tasks.each do |task| %>
  <td><%= link_to task.description, task_path(task)  %></td>
  <td><%= task.user.first_name %></td>
  <td><%= task.value %></td>
  <td><%= task.task_type %></td>
  <td><%= task.frequency %></td
  <td><%= task.active %></td>
  <td><%= task.due_by %></td>
  <%= button_to "Task Completed", new_completed_task_path(:completed =>[:task_id =>
  task.id, :task_value => task.value}) %>         
<%end%>

在我的completed_task_controller中,我有:

def new
  @completed_task = CompletedTask.new(params[:completed]) 
end

def create
  @completed_task = CompletedTask.new(completed_task_params)
end

当我单击按钮完成任务时,我希望它在completed_tasks表中创建一条记录,但是父表中的参数不会从新动作流向创建动作。我猜测它与我设置的强参数有关:

private
def set_completed_task
  @completed_task = CompletedTask.find(params[:id])
end

def completed_task_params
 params.require(:completed_task).permit(:task_id, :task_value)    
end

以下是我遇到的错误:

ActiveModel::ForbiddenAttributesError
Extracted source (around line #19):

def new
  @completed_task = CompletedTask.new(params[:completed])
end

任何想法???

1 个答案:

答案 0 :(得分:3)

当您调用new方法时,此时表单中没有返回任何内容(它还没有被dsiplayed,但是)

你应该做的

def new
  @completed_task = CompletedTask.new
end

返回表单时,create方法通常会执行

def create
  @completed_task = CompletedTask.new(completed_task_params)
  if @completed_task.save
    # stuff to do when the record is saved, maybe redirect to show page or index
  else
    # stuff to do if record is not saved... probably redisplay new format with errors
  end  
end 

编辑:澄清一下,方法completed_task_params(您正确编码)实质上将表单属性标记为可接受。如果您完成了CompletedTask.new(params[:completed_task])强参数,那么由于属性未被标记为允许,因此您会感到不满意。