2014-02-10 41 views
0

有人可以解釋爲什麼before_save:encrypt_password在我的數據庫中創建password_hash和password_salt,但before_create:encrypt_password不是?是否有一些我缺少的Rails 4或Rails規範?下面的代碼片段。Rails 4從頭開始驗證:before_create vs before_save

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 
+0

取決於你創建對象時......它已經有密碼了嗎?順便說一句回調是邪惡的 – apneadiving

回答

1

在「創建」方法中,您正在初始化AND保存在同一時間。

當你有一個「保存」方法時,你必須先初始化然後保存它。

所以,我想這不適用於before_create,只是因爲這一刻你還沒有在初始化實例的密碼。

而在「before_save」中,它的工作原理是因爲如果你保存了某些東西,你已經用密碼初始化了一個實例,然後它可以被加密。

記住: create = new +保存在同一時間,所以before_create你什麼也沒有。 並保存必須與已經初始化的東西。

我希望我已經清楚!

0

不幸的是,before_create:encrypt_password和before_save:encrypt_password都正確地將加密字符串保存到數據庫中,如下所示:after_validation。肯定會有一些我不小心修復的錯誤,或者是我沒有修復的錯誤,並且現在已經消失了。