Reputation: 13
So I have a nested resource, where todolist
is the parent and the todoitem
is the child.
resources :todolists do
resources :todoitems
end
I have created an Add Todo List
link where it invokes new_todolist_todoitem
found in routes.rb
.
new_todolist_todoitem GET /todolists/:todolist_id/todoitems/new(.:format) todoitems#new
In my todolists/show.html.erb
file, I have included this line of code:
<%= link_to 'Add Todo Item', new_todolist_todoitem_path(@todolist.id) %>
And in my todoitems/_form.html.erb
, I have also included the nested parameters inside of it:
<%= form_for([@todolist, @todoitem]) do |f| %> --> Error is on this line
<% if @todoitem.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@todoitem.errors.count, "error") %> prohibited this todoitem from being saved:</h2>
In my todoitems_controller.rb
, I put these down for new
and create
methods:
# GET /todoitems/new
def new
@todoitem = Todoitem.new
end
# POST /todoitems
# POST /todoitems.json
def create
@todoitem = @todolist.todoitems.new(:todoitem_params)
respond_to do |format|
if @todoitem.save
format.html { redirect_to @todoitem, notice: 'Todoitem was successfully created.' }
format.json { render :show, status: :created, location: @todoitem }
else
format.html { render :new }
format.json { render json: @todoitem.errors, status: :unprocessable_entity }
end
end
end
The problem is that I keep getting an error stating:
undefined method `todoitems_path' for #<#<Class:0x007feaa79e8da8>:0x007feaa5d0d878>
If anybody has a possible solution to fix this problem or suggestions, it would be greatly appreciated. Thank you!
P.S. According to the stack trace, the Parameters Request is: {"todolist_id"=>"2"}
Upvotes: 0
Views: 223
Reputation: 11823
You are not setting @todolist
instance variable in your controller code but you are using it in the form_for [@todolist, @todoitem]
tag. Make sure you have one set in your controller. Usually it is done in the before_filter
like so:
class Todoitem
before_filter :set_todolist
def set_todolist
@totolist = Todolist.find(params[:todolist_id])
end
end
Upvotes: 1
Reputation: 1983
A couple things to note about this and hopefully it solves your issue.
In your todolists/show.html.erb
, you can just pass the @todolist
in your link_to
<%= link_to 'Add Todo Item', new_todolist_todoitem_path(@todolist) %>
Then some changes need to be made to your controller:
todoitems_controller.rb
before_action :set_todolist
def create
@todoitem = Todoitem.new(todoitem_params)
# Assuming Todoitem belongs_to Todolist
@todoitem.todolist_id = @todolist.id
...
end
private
def set_todolist
@todolist = Todolist.find(params[:todolist_id]
end
Make sure your params are correct as well.
Upvotes: 0