有人能解释一下为什么before_save :encrypt_password会在我的数据库中创建password_hash和password_salt,而before_create :encrypt_password不会吗?我是否遗漏了一些Rails 4或Rails规范?下面的代码片段。
include MembersHelper
class Member < ActiveRecord::Base
include ActiveModel::Validations
has_many :parents, through: :reverse_relationships, source: :parent
has_many :children, through: :relationships, source: :child
has_many :relationships, foreign_key: "parent_id", dependent: :destroy
has_many :reverse_relationships, foreign_key: "child_id", class_name: Relationship, dependent: :destroy
has_many :spouses, through: :spouse_relationships, source: :spouse
has_many :spouse_relationships, foreign_key: "member_id", dependent: :destroy
has_many :images
accepts_nested_attributes_for :parents, reject_if: proc { |attributes| attributes['first_name'].blank? && attributes['first_name'].blank? }
accepts_nested_attributes_for :spouses, reject_if: proc { |attributes| attributes['first_name'].blank? && attributes['first_name'].blank? }
accepts_nested_attributes_for :children, reject_if: proc { |attributes| attributes['first_name'].blank? && attributes['first_name'].blank? }
attr_accessor :password
#####
before_save :encrypt_password ##### this does not work if i change it to before_create
#####
before_save :nil_or_downcase
before_create :nil_or_downcase
after_create :set_oldest_ancestor
before_create { create_token(:remember_token) }
before_destroy [ :set_ancestor_for_children, :destroy_spouse_id_of_spouse ]
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret( password, password_salt)
end
end
发布于 2014-02-11 02:32:16
在"create“方法中,您同时进行初始化和保存。
当你有一个" save“方法时,你必须首先初始化它,然后保存它。
所以,我猜这对before_create不起作用,只是因为此时你在初始化的实例中仍然没有密码。
在"before_save“中,它是有效的,因为如果你要保存一些东西,你已经用密码初始化了一个实例,然后它就可以被加密了。
记住: create = new + save的同时,所以before_create你没有任何东西。save必须与已经初始化的内容一起使用。
我希望我已经讲清楚了!
发布于 2014-02-11 03:05:31
遗憾的是,与:after_validation一样,before_create :encrypt_password和before_save :encrypt_password都正确地将加密字符串保存到数据库中。一定是我无意中修复了一些bug,或者是我没有修复的bug,只是暂时消失了。
https://stackoverflow.com/questions/21683865
复制相似问题