0

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?

1
  • Why are you making has_register_session? a method on the class rather than the instance? Commented Apr 4, 2012 at 19:00

2 Answers 2

5

self when you define the method refers to the UsersController class object, but within the instance method new, self refers to the instance of UsersController.

  1. You can either make your method an instance method:

    def has_register_session?
      # code
    end
    

    You can then get rid of the self when calling has_register_session? in new as well.

  2. Or call the method on the class:

    if UsersController.has_register_session?
      # code
    end
    

    instead of referencing UsersController explicitly you could do self.class.

Note that you likely want the first solution: making has_register_session? an instance method.

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

Comments

0

By doing def self.blah you've created a class method whereas you want an instance method.

You might also want to make the method protected - all public methods are exposed as actions by default.

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.