0

I have a member model with a reset_token method (which assigns a user a new token in order to send them an email to reset their password). But update_attribute never saves anything in the database. I have :new_password_token assigned to attr_accessible and attr_accessor. The log picks up the salt and token but it always returns nil

def self.reset_token(email)
  member = find_by_email(email)
  if member
    #Reset token, and then send email
    salt = BCrypt::Engine.generate_salt
    logger.error "Salt is #{salt}"
    token = BCrypt::Engine.hash_secret(email, salt)
    logger.error "token is #{token}"
    if member.update_attribute(:new_password_token, token)
      member
    end
  end
  nil
end

Controller method in which it is called:

def reset_password
  @member = Member.reset_token(params[:email])
  if @member
    redirect_to(root_url, :notice => "Please check your email for instructions")
  else
    redirect_to(root_url, :notice => "Sorry we have no record of your account")
  end
end
Msencenb
  • 5,675
  • 11
  • 52
  • 84
  • it returns `nil` because `nil` is the last statement. `return member` or remove `nil` from the method. Regard to `update_attribute`, are you sure it's not a validation? – Vasiliy Ermolovich Jul 09 '11 at 22:13
  • You might add an `else` statement after your `if member.update....` line, something like `else logger.error member.errors`. – Dylan Markow Jul 09 '11 at 22:18
  • Ok so its not returning nil anymore ( I guess I thought it would return on the member... you were correct nash). Problem now is that its not saving to the database. I have tried changing it to update_attributes, also tried setting the variable with dot notation and then calling member.save but it still isn't saving for some reason – Msencenb Jul 09 '11 at 22:37

1 Answers1

2

Try removing attr_accessor from your model. attr_accessor is creating reader and writer methods for new_password_token. The writer method is equivalent to:

def new_password_token=(new_password_token)
  @new_password_token = new_password_token
end

So when you update_attribute it is just setting an instance variable on your object and bypassing the database altogether.

Bradley Priest
  • 7,438
  • 1
  • 29
  • 33