未定义的方法`todo_lists'为零:NilClass
问题描述:
我正在开发一个todolist应用程序,其中应用程序将仅显示基于其user_id的用户待办事项列表。这意味着如果用户登录,数据库将只显示具有相同user_id的待办事项列表。未定义的方法`todo_lists'为零:NilClass
但即时得到这个错误:
undefined method `todo_lists' for nil:NilClass
# GET /todo_lists/new
def new
@todo_list = current_user.todo_lists.build
end
# GET /todo_lists/1/edit
todo_lists_controller.rb
class TodoListsController < ApplicationController
before_action :set_todo_list, only: [:show, :edit, :update, :destroy]
def index
@todo_lists = TodoList.all
end
def new
@todo_list = current_user.todo_lists.build
end
def create
@todo_list = current_user.todo_lists.build(todo_list_params)
respond_to do |format|
if @todo_list.save
format.html { redirect_to @todo_list, notice: 'Todo list was
successfully created.' }
format.json { render :show, status: :created, location: @todo_list }
else
format.html { render :new }
format.json { render json: @todo_list.errors, status: :unprocessable_entity }
end
end
end
private
def set_todo_list
@todo_list = TodoList.find(params[:id])
end
def todo_list_params
params.require(:todo_list).permit(:title, :description)
end
end
有像破坏,更新,显示和编辑,但我不粘贴到此处因为我觉得其他的方法它没有任何关系解决这个问题。我试图将todo_lists
更改为其他,如@todo_lists
,TodoLists
和todo_list
但他们都没有工作。
我在各种网站搜索解决方案,但我没有找到任何。我真的认为,这里的主要问题是,我不明白写什么代码因为我有不同的代码,像我上面说的(@todo_lists
等)相同的意思。有点蠢呀,还是试着这里
P/S 2的时间学习轨道的^^” SRY我蹩脚的英语
答
的问题是,current_user
为零。
如果您使用的是devise
,请在您的TodoListsController
中添加before_action :authenticate_user!
。
如果没有,那么类似的代码添加到您的application_helper.rb
def current_user
User.first
end
可以粘贴什么'current_user'的方法定义是什么?基本上你需要调试'current_user' – AnkitG
@AnkitG你的意思是'def current_user'?在控制器中? – Nami
是的,但是你已经定义了'current_user'。你的'current_user'是'nil'。 – AnkitG