I’m new with RoR and I have a controller (UsersController) where I wish to verify the existence of a certain session before anything. Since the session verification code is the same for several methods and I don’t want to repeat myself, I decided to make a new method in my controller to check the sessions:
class UsersController < ApplicationController
def index
end
def show
end
def new
if self.has_register_session?
# Does something
else
# Does something else
end
end
def edit
end
def create
end
def update
end
def destroy
end
def self.has_register_session?
# true or false
end
end
And when I run the page /users/new, I got this error:
undefined method `has_register_session?' for #<UsersController:0x1036d9b48>
Any idea?
selfwhen you define the method refers to theUsersControllerclass object, but within the instance methodnew,selfrefers to the instance ofUsersController.You can either make your method an instance method:
You can then get rid of the
selfwhen callinghas_register_session?innewas well.Or call the method on the class:
instead of referencing
UsersControllerexplicitly you could doself.class.Note that you likely want the first solution: making
has_register_session?an instance method.