I watched the RailCasts tutorial #274 on Remember Me and Reset Password. The code he adds is the following inside user.rb
def send_password_reset
generate_token(:password_reset_token)
save!
UserMailer.password_reset(self).deliver
end
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
Here what I don’t understand is why the save! call inside send_password_reset? Also, I’m not familiar with the syntax in generate_token: self[column]=. Is this the way to set a column inside a database table?
Here’s the create action of the password_resets_controller
def create
user = User.find_by_email(params[:email])
user.send_password_reset if user
redirect_to root_path, notice: "Email sent with password reset instructions."
end
save!saves the object and raises an exception if it fails.self[column]=, is a slight meta-programming.Usually, when you know the column name, you’d do:
self.password_reset_token=. Which is the same asself[:password_reset_token]=orself["password_reset_token"]=.So it’s easy to abstract it a bit passing column name as string/symbol.
Clearer?