7.1 adding passwords to user model.

1. rake db:reset

 

this command is very useful, it will clear the old sample data from database, so we again have a clean database

 

2. here, we will just use plain password, with bad secure, we will talk about password security later.

 

3. again, we will start from test!!!!

 

now in the sample data in the spec test, should change to:

 

 

before(:each) do
  	@attr = {
		:name => "sb",
		:email => "sb@sb.com",
		:password => "123456",
		:password_confirmation => "123456"
	}
end

 below are some password validation test:

 

 

describe "password validation" do
    it "should require a password" do
        User.new(@attr.merge(:password=>"", :password_confirmation => "")).should_not be valid
    end
end
 

 

4.  We won't add a password attribute to the database, instead, we will store a encrypted_password attribute, so for the password, we will introduce a virtual attribute, which is an attr that not corresponding to a colume in the database.

 

the way to define a virtual attribute is to use attr_accessor method.

this attribute will not be written into database, will only exist in memory.

 

for the password_confirmation, we even will not have a virtual attribute for it, instead, it is used in the validation:

 

validates :password, :confirmation => true

this line will auto create a virtual attribute called "password_confirmation", and confirm it matches the password attribute.

 

 

 

attr_accessor :password      (this line is to create a virtual attribute)

attr_accessible :name, :email, :password, :password_confirmation

 

the second line is used to prevent mass assignment vulnerability.

 

 

5. next we will add a column into users table.

 

a way to test if a model respond to a method:

 

user = User.new

user.respond_to? :password

user.respond_to? :encrypted_password

 

rails g migration add_password_to users encrypted_password:string

 

the "_to_users" make rails automatically construct a migration to add columns to the users table. and by including the 2nd argument, we give Rails enough info to construct the entire migration for us.

 

ok, next, 

 

rake db:migrate

rake db:test:prepare

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值