Search code examples
ruby-on-railsruby-on-rails-3activerecordupdate-attribute

Rails 3 update_attribute not firing


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

Solution

  • 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.