7.1.3 active record callback
chapter 7.1.3
now that our user model has an attr for storing password, we need to arrange to generate and save an encrypted password when save user to the database.
the technique of doing this is callback.
we will use before_save callback to create the encrypted_password.
1. start from test again.
we just need to make sure the saved encrypted password is not blank.
it "should set the encrypted password" do
@user.encrypted_password.should_not be_blank
end
2. next, we will registe a callback called encrypt_password by passing a symbol of that name to before_save method.
before_save :encrypt_password
private
def encrypt_password
self.encrypted_password = encrypt(password)
end
def encrypt(string)
string
end
note:
the two method are private methods, it is a good habit to have indentation for private method, which make you fastly deduce this is a private method, or you may get into trouble some time.
don't care the difference of private and protect, just use private is enough for you!!!!!!
it is a good practice to make method private unless they are needed for the public interface!!
These are one-line method, (the best kind!!!)
self refer to the object itself. it can't be omitted, or encrypted_password will be a common local variable!!!!
but the "password" at the right side can omit self, as it is on the right side!!!
上一篇: AcWing寒假每日一题总结(一)
下一篇: 使用openssl生成证书
推荐阅读
-
[Rails] Active Record Queries
-
[Rails] Active Record Migration
-
Active Record: Sexy migrations
-
7.1.3 active record callback
-
yii2中使用Active Record模式的方法
-
Active Record batch processing in parallel processes
-
Active Record batch processing in parallel processes
-
Yii框架官方指南系列26——使用数据库:关系型 Active Record
-
Yii框架官方指南系列25——使用数据库:Active Record
-
yii2中使用Active Record模式的方法_php实例