CirclesController#中的NoMethodError为nil:NilClass添加未定义的方法'circle'

时间:2018-10-21 18:07:47

标签: ruby

这是我得到的错误:

提取的来源(围绕第14行):

12 
13  # Current_user wants to room with user_to. Neither have a circle. Create a new circle and add both
14  if current_user.circle.empty? && user.circle.empty?
15     circle = Circle.new
16     circle.users << current_user
17     circle.users << user

这是屏幕截图 https://i.stack.imgur.com/jG198.png

**CIRCLE CONTRONER**
class CirclesController < ApplicationController
    def index
        @circles = Circle.all
    end

    def add
        # binding.pry 
        # if !current_user.landlord && current_user.memberships.any? 
        #     redirect_to user_path(current_user), notice: 'You already have a circle! Leave your current circle to join a different one.' 
        # else 
            @circle = Circle.add_user_to_circle(current_user, params[:user_to_add])

        if @circle && @circle.save
            redirect_to user_path(current_user), notice: 'Member was successfully added to circle!'
        elsif @circle == false
            redirect_to user_path(current_user), notice: 'User already in circle!' 
        else
            redirect_to user_path(current_user), notice: 'An error occurred, and the member could not be added to a circle.'
        end 
        # end
    end

    def show
         @circle = Circle.all
    end
end

上面的代码是CircleController。我不知道这是怎么了。 任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

在第14行中,您应先检查 current_user 是否已初始化,然后再使用任何方法。
更改
if current_user.circle.empty? && user.circle.empty?

if current_user && current_user.circle.empty? && user.circle.empty?

if !current_user.nil? && current_user.circle.empty? && user.circle.empty?

它不会解决您的其他问题,但可以防止 NoMethodError 错误。
此外,您可能要在使用方法 #empty 之前以同样的方式检查圆圈

我没有深入分析您的代码,但是在使用某些对象之前,通常先检查一下是否存在(如果可能不存在)。