Reputation: 23
Here's the problem I've been working on for the last few days:
I have task and completed_task models:
class Task < ActiveRecord::Base
belongs_to :user
has_many :completed_tasks
end
class CompletedTask < ActiveRecord::Base
belongs_to :task
end
I have a form that says:
<% @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%>
In my completed_task_controller, I have:
def new
@completed_task = CompletedTask.new(params[:completed])
end
def create
@completed_task = CompletedTask.new(completed_task_params)
end
When I click on the button to complete a task, I want it to create a record in the completed_tasks table but the params from the parent table are not flowing from the new action to the create action. I'm guessing it has to do with the strong parameters which I have set as:
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
Here is the error I am getting:
ActiveModel::ForbiddenAttributesError
Extracted source (around line #19):
def new
@completed_task = CompletedTask.new(params[:completed])
end
Any ideas???
Upvotes: 2
Views: 67
Reputation: 36860
When you call the new
method, at that point nothing has been returned from the form (it hasn't even been dsiplayed, yet)
You should just do
def new
@completed_task = CompletedTask.new
end
When the form is returned, then the create
method would typically do
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
EDIT: to clarify, the method completed_task_params
(which you correctly coded) essentially flags the form attributes as acceptable. Had you done CompletedTask.new(params[:completed_task])
strong parameters would've been unhappy as the attributes weren't flagged as permitted.
Upvotes: 3