AFusco
AFusco

Reputation: 474

Undefined method error when accessing a field inside a model

My model looks like this

require 'bcrypt'

class Authorization < ActiveRecord::Base
  before_save :encrypt_password

  # some validations and other methods




  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_encrypted = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end


  def self.authenticate(hash)
    auth = where(provider: 'email', email: hash[:email])
    if auth and auth.password_encrypted == BCrypt::Engine.hash_secret(hash[:password], auth.password_salt)
      auth
    else
      nil
    end
  end

end

but when in my controller I call Authorization.authenticate(hash) with the hash given by params.permit(:email, :password) I get undefined method `password_encrypted' when it actually exists.

Upvotes: 0

Views: 180

Answers (1)

Helios de Guerra
Helios de Guerra

Reputation: 3475

Your authenticate class method is returning a relation instead of an instance, which is why your instance variables are not available.

You'll have to modify the first line of your authenticate method to look something like so:

auth = where(provider: 'email', email: hash[:email]).first

Or maybe

auth = find_by(provider: 'email', email: hash[:email])

Something along those lines to make sure you're dealing with an instance of Authorization rather than the relation returned by the where call (even if it's only returning one record).

Upvotes: 1

Related Questions