在rals4/5中使用has_secure_password 时,在官方文档是这么说明的:
require 'bcrypt'
class User < ActiveRecord::Base
# users.password_hash in the database is a :string
include BCrypt
def password
@password ||= Password.new(password_hash)
end
def password=(new_password)
@password = Password.create(new_password)
self.password_hash = @password
end
end
def create
@user = User.new(params[:user])
@user.password = params[:password]
@user.save!
end
def login
@user = User.find_by_email(params[:email])
if @user.password == params[:password]
give_token
else
redirect_to home_url
end
end
save是说明了会调用内置的加密方法加密,但是使用update却也一样可以使用, github没说update有什么操作,谷歌发现了update与save的关系:
Update methods cheat sheet (for Rails 4):
- update_attributes = assign_attributes + save
- attributes= = alias of assign_attributes
- update = alias of update_attributes
Source:
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_assignment.rb
Another cheat sheet:
http://www.davidverhasselt.com/set-attributes-in-activerecord/#cheat-sheet