zer0uno
zer0uno

Reputation: 8030

Instance variable Rails


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.

Upvotes: 0

Views: 109

Answers (2)

Debadatt
Debadatt

Reputation: 6015

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

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

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).

Upvotes: 3

Related Questions