2011-03-02 44 views
1

我有一個錯誤,在關聯的模型中,父模型的外鍵在關聯模型的表中作爲NULL來到。爲了追蹤爲什麼發生這種情況,我希望每次給屬性賦值時寫入日誌文件(即每次調用attr=方法)。如何截取屬性的賦值?

我該怎麼做? Rails是否已經允許通過某種我不知道的方式來完成這項工作?

回答

1

你可以通過簡單覆蓋attr =方法來完成。例如:

class User 
    def username= username 
    Rails.logger.info "Setting username with #{username}" 
    write_attribute :username, username 
    end 
end 

您也可以通過鏈接方法來完成此操作。例如:

class User 
    alias :username_old= :username= 
    def username= username 
    Rails.logger.info "Setting username with #{username}" 
    self.username_old = username 
    end 
end 
1

我認爲你可以使用回調方法(before_save)來檢查你的對象的狀態。 以下可能會幫助你...

 
article = Article.find(:first) 
article.changed? #=> false 

# Track changes to individual attributes with 
# attr_name_changed? accessor 
article.title #=> "Title" 
article.title = "New Title" 
article.title_changed? #=> true 

# Access previous value with attr_name_was accessor 
article.title_was #=> "Title" 

# See both previous and current value with attr_name_change accessor 
article.title_change #=> ["Title", "New Title"] 
+0

謝謝,我試過了,但它並沒有幫助 – Zabba 2011-03-02 07:53:24