NoMethodError в CirclesController # добавить неопределенный метод `circle 'для nil: NilClass - PullRequest
0 голосов
/ 21 октября 2018

Это ошибка, которую я получил:

Извлеченный источник (около строки # 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 голосов
/ 22 октября 2018

В строке # 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 ?

Я не анализировал ваш код подробно, но стандартная практика - проверять какой-либо объект, если он существует (если он может не существовать), прежде чем использовать его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...