login - undefined method 'hashed_password' Agile Web developpement with rails -


i'm following iteration 13 of agile web developpement, user login.

i create migration add 2 columns user model : hashed_password , salt.

  • creation of users works
  • login fails, due error undefined method 'hashed_password' in method 'authenticate'

the problem :

  • in rails console, can fetch user.first.hashed_password, seems ok :-)
  • i outputted user fecth, , not nil
  • i tried output user.hashed_password did in rails console, throws same error :

nomethoderror (undefined method hashed_password' #<activerecord::relation:0x00000003e6c3c0>): app/models/user.rb:21:inauthenticate' app/controllers/sessions_controller.rb:6:in `create'

this user model :

require 'digest/sha2'  class user < activerecord::base has_and_belongs_to_many :products has_many :created_products, :class_name => "product", :foreign_key => :product_id  default_scope :order => "username asc"   # attributs pour le login (livre) validates :username, :presence => true, :uniqueness => true validates :password, :confirmation => true attr_accessor :password_confirmation attr_reader :password validate :password_must_be_present  def user.authenticate(name, password)     logger.debug "---------- beginning of authenticate"     if user = user.where(:username => name)        logger.debug "utilisateur = #{user.inspect}"   # ok , not nil       logger.debug "utilisateur hashed pw = #{user.hashed_password}" # error           if user.hashed_password == encrypt_password(password, user.salt)             return user         end     end end  def user.encrypt_password(password, salt)     digest::sha2.hexdigest(password + "wibble" + salt) end  def password=(password)     @password = password     if (password.present?)         generate_salt         self.hashed_password = self.class.encrypt_password(password, salt)     end end   private      def password_must_be_present         errors.add(:password, "mot de passe manquant") unless hashed_password.present?     end      def generate_salt         self.salt = self.object_id.to_s + rand.to_s     end  end 

user.where(:username => name) returning activerecord::relation object (hence error message seeing). try changing if statement to:

if user = user.where(:username => name).first 

that set take first matching user, instance of user , have hashed_password field. if no user matches, you'll nil.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -