未定义的方法`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,TodoListstodo_list但他们都没有工作。

我在各种网站搜索解决方案,但我没有找到任何。我真的认为,这里的主要问题是,我不明白写什么代码因为我有不同的代码,像我上面说的(@todo_lists等)相同的意思。有点蠢呀,还是试着这里

P/S 2的时间学习轨道的^^” SRY我蹩脚的英语

+0

可以粘贴什么'current_user'的方法定义是什么?基本上你需要调试'current_user' – AnkitG

+0

@AnkitG你的意思是'def current_user'?在控制器中? – Nami

+0

是的,但是你已经定义了'current_user'。你的'current_user'是'nil'。 – AnkitG

的问题是,current_user为零。

如果您使用的是devise,请在您的TodoListsController中添加before_action :authenticate_user!

如果没有,那么类似的代码添加到您的application_helper.rb

def current_user 
    User.first 
end 
+0

即时通讯使用设计和添加'before_action:authenticate_user!'..这意味着只有身份验证用户可以创建一个todolist,对吧? – Nami

+0

是的,如果用户没有登录,他会重定向到登录页面。 –

+0

它的工作!谢谢 ! – Nami