class TodoItemsController < ApplicationController
# use callbacks instead of repeating yourself
before_action :set_todolist, only: [:new, :create, :index]
def index
@todo_items = @todo_list.todo_items
@todo_item = TodoItem.new
end
def create
@todo_item = @todo_list.todo_items.new(todo_list_params)
if @todo_item.save
redirect_to [@todo_list, :todo_items]
else
render :new
end
end
private
def set_todolist
@todo_list = TodoList.find(params[:todo_list_id])
end
# use a private method for your params whitelist for readibility
# it also lets you reuse it for the update action
def todo_list_params
params.require(:todo_item)
.permit(:description, :complete_at)
end
end
You where setting a different instance variable (@new_todo
) in you index action. The polymorphic route helpers that look up the route helpers from [@todo_list, @todo_item]
call compact on the array. So if @todo_item
is nil its going to call todo_lists_path
instead - ooops!
You alway also need to consider how you are going to respond to invalid data. Usually in Rails this means rendering the new view. If you are rendering the form in another view such as the index view it can get kind of tricky to re-render the same view as you have to set up all the same data as that action which leads to duplication.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…