anonn023432
anonn023432

Reputation: 3120

Undefined method when calling model method in controller

I have a class method in my User model:

def self.method_name
  ...
end

In a controller, I need to call this method on a User instance obtained through association:

@user = game_play.player.user

As expected, it threw a no method error because it's a class method.

What is the way to call the method in this case?

EDIT: Adding code for question clarification

@user = @game_play.client.user.
@token = @user.set_login_bypass_token

My model:

def set_login_bypass_token
  #We generate a raw token and an encrypted version of the same token
  raw, enc = Devise.token_generator.generate(User, :login_bypass_token)
  self.login_bypass_token = enc
  self.login_bypass_token_set_at = Time.now
  self.save(validate: false)
  #Raw token is sent to the user via email to provide auto-login
  raw
end

The error:

PG::UndefinedColumn: ERROR:  column users.login_bypass_token does not exist

Notice the error has it as users.login_bypass_token instead of set_login_bypass_token

Upvotes: 2

Views: 1328

Answers (2)

Pablo
Pablo

Reputation: 3005

EDIT:

My first answer was before you mentioned Devise and assuming you didn't know if you needed a class or instance method. It's clear that your method must be an instance one.

I think you are trying to apply something you found here: https://stackoverflow.com/a/30857087/3372172

This requires that you add a new field to the users database, to manage the :login_bypass_token. Because you will use this column later to perform a find_by. Devise does not add this column to the database.

PREVIOUS ANSWER

If the method needs to access instance variables (which means it acts differently depending the specific object in the User class), it should be an instance method, defined without the self keyword.

If it is a class method, it cannot depend on any attribute from a specific object, and you cannot call it from an instance of the class.

You must decide if it's really a class method or an instance method. ` If you need a class method to be called from an instance, you can do this (but I don't know why you could need it).

class User
  def self.method_name
    # blablabla
  end

  def method_name
    User.method_name
  end
end

Upvotes: 1

Riley Thompson
Riley Thompson

Reputation: 61

Should be using an instance method instead of a class method. I'm not sure how you would get an error where it's looking for an attribute on the model since those can only be defined in the schema. If you're adding a regular instance method within the model it should work correctly.

Upvotes: 0

Related Questions