[英]don't understand some code from a RailsCast tutorial
I watched the RailCasts tutorial #274 on Remember Me and Reset Password. 我在“记住我并重置密码”上观看了RailCasts教程#274。 The code he adds is the following inside user.rb
他添加的代码在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!
在这里,我不明白的是为什么要save!
call inside send_password_reset
? 调用send_password_reset
内部? Also, I'm not familiar with the syntax in generate_token
: self[column]=
. 另外,我对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
这是password_resets_controller
的create
动作
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. self[column]=
,是一个轻微的元编程。
Usually, when you know the column name, you'd do: self.password_reset_token=
. 通常,当您知道列名时,可以这样做: self.password_reset_token=
。 Which is the same as self[:password_reset_token]=
or self["password_reset_token"]=
. 与self[:password_reset_token]=
或self["password_reset_token"]=
。
So it's easy to abstract it a bit passing column name as string/symbol. 因此,很容易将其作为字符串/符号传递给列名。
Clearer? 更清晰?
1) save!
1) save!
is like save
, but raise a RecordInvalid
exception instead of returning false
if the record is not valid. 类似于save
,但是引发RecordInvalid
异常,而不是如果记录无效则返回false
。
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. 2) self[column]=
用于设置用户列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.