0


I have the following two methods in my CommandsController

class CommandsController < ApplicationController
.
.
.

def userslist
    @command = Command.find_by(id: params[:id])
    @users_list = @command.users.paginate(page: params[:page], per_page: 10)
end

def deleteuser
    user = User.find_by(id: params[:id])
    user.commands.destroy(@command)
    flash[:success] = "Utente eliminato dalla lista con successo"
    redirect_to list_path(@command)
end
.
.
.  

end

When I execute deleteuser method I receive the following error:
Command(#31369720) expected, got NilClass(#19349600) related to line user.commands.destroy(@command) which means that @command is nil, but why is it so? Isn't @command an instance variable visible by all methods in my class?


P.S. To call deleteuser method I have to go through userslist method, so @command is certainly not nil.

2
  • @command can not be available to deleteuser method. you need to declare again Commented Sep 24, 2013 at 9:59
  • but why can't @command be available? it's an instance variable, isn't it? Commented Sep 24, 2013 at 10:02

2 Answers 2

3

Your @command instance variable is not set when you call deleteuser method, so it evaluates to nil.

The reason you have this error is you probably misunderstand how the Rails controllers work. Rails creates new instance of your commands controller with every request regarding this controller, so even if you set @command instance variable in previous action, with new request it is nil again.

I suggest learning some Rails/Ruby basics and conventions (including naming conventions).

Sign up to request clarification or add additional context in comments.

1 Comment

but it is set by the userslist method previously
0

You can make another private method to declare @command and call it in before_filter after the declaration of the controller class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.