2017-07-08 72 views
0

如果字段更改且只有其不是記錄記錄,則需要在rails4應用程序中執行掛鉤。before_save,如果字段值發生變化,新記錄除外

我知道我可以做...

before_save :reset_confirmation, if: :email_changed? 
    def reset_confirmation 
    self.confirmed_at = nil 
    self.confirmation_sent_at = nil 
    end 

,我敢肯定,這個工程......

before_save :reset_confirmation, unless: new_record? 
    def reset_confirmation 
    self.confirmed_at = nil 
    self.confirmation_sent_at = nil 
    end 

但我如何將二者結合起來,或有更簡單實現我想要的東西的方法,我正在推翻一些東西。如果有幫助,該字段(電子郵件)在創建之後將始終包含一個值。

回答

1

您可以在回調中使用多個條件,如:

before_save :reset_confirmation, if: :email_changed?, unless: :new_record? 

def reset_confirmation 
    self.confirmed_at = nil 
    self.confirmation_sent_at = nil 
end 

或者,你可以添加其他的方法來檢查這兩個條件,例如:

before_save :reset_confirmation, if: :email_changed_and_its_not_new_record? 

def reset_confirmation 
    self.confirmed_at = nil 
    self.confirmation_sent_at = nil 
end 

def email_changed_and_its_not_new_record? 
    email_changed? && !new_record? 
end 

你可以找到更多信息有條件的回調here

0

我這個在去年底...

before_update :reset_confirmation, if: :email_changed? 
    def reset_confirmation 
    self.confirmed_at = nil 
    self.confirmation_sent_at = nil 
    end 

與邏輯之中只有before_update運行在現有的記錄,這需要新的記錄問題的關心,現在它不會踏進該方法除非滿足條件來重置字段。

0

不知類的可讀性和可維護性提高回調時被明確setter方法代替:

def email=(new_email) 
    unless new_email == email 
    self.confirmed_at = nil 
    self.confirmation_sent_at = nil 
    write_attribute(:email, new_email) 
    end 
end 
相關問題