Reputation: 5392
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
Upvotes: 0
Views: 83
Reputation: 115531
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 as self[:password_reset_token]=
or self["password_reset_token"]=
.
So it's easy to abstract it a bit passing column name as string/symbol.
Clearer?
Upvotes: 5
Reputation: 3742
1) save!
is like save
, but raise a RecordInvalid
exception instead of returning false
if the record is not valid.
Example from my console:
User.new().save # => false
User.new().save! # ActiveRecord::RecordInvalid: Validation failed: Password can't be blank, Email can't be blank
2) self[column]=
there for setting users column.
Upvotes: 1