9
當我使用IRB創建一個新的模型實例並保存時,沒有打印出來給控制檯,而且我得到一個「ActiveRecord :: StatementInvalid:Mysql :: Error:Column'user_id'不能爲null」的錯誤,所以我假設before_save沒有被調用。我無法弄清楚爲什麼。我甚至嘗試過使用before_save過濾器。這裏是我的代碼:爲什麼before_save沒有被我的ActiveRecord模型調用?
require 'secure_resource/secure_resource_encryption'
class Database < ActiveRecord::Base
belongs_to :username_encryption, :class_name => "Encryption", :foreign_key => :username_encryption_id
belongs_to :password_encryption, :class_name => "Encryption", :foreign_key => :password_encryption_id
# Virtual attribute to retrieve the decrypted username.
def username
if self.username_encryption.nil?
return nil
end
begin
return self.username_encryption.encryption
rescue SecureResourceError
raise SecureResourceError
end
end
# Provides a way to reset the username.
def username=(username)
if self.username_encryption.nil?
self.username_encryption = Encryption.new
self.username_encryption.encryption = username
end
end
# Virtual attribute to retrieve the decrypted password.
def password
if password_encryption.nil?
return nil
end
begin
return password_encryption.encryption
rescue SecureResourceError
raise SecureResourceError
end
end
# Provides a way to reset the password.
def password=(password)
if self.password_encryption.nil?
self.password_encryption = Encryption.new
self.password_encryption.encryption = password
end
end
def before_save
p 'ZZZZZZZZZZZZZZZ'
p self.user_id.to_s + ' ZZZZZZ'
p 'ZZZZZZZZZZZZZZZ'
self.username_encryption.user_id = self.user_id
self.username_encryption.save
self.username_encryption_id = self.username_encryption.id
self.password_encryption.user_id = self.user_id
self.password_encryption.save
self.password_encryption_id = self.password_encryption.id
end
end
啊,所以MySQL驗證過程中發生錯誤。出於某種原因,我認爲這是在保存期間發生的。我會試試看看會發生什麼。我如何明確地告訴驗證是否通過? – 2011-06-10 18:18:18
事情是,在IRB中,當我創建一個新的數據庫實例,設置參數,並調用database.valid?時,返回true。那麼這怎麼可能是一個驗證問題? – 2011-06-10 18:32:13
@Chad啊,我沒有仔細閱讀。如果MySQL提出錯誤,您的'before_validation' *和*'before_save'回調已經觸發,Rails正在與數據庫進行通話。其中一個'user_id'字段爲空。嘗試使用'logger.info'而不是'puts' /'p',其中*不會寫入Rails中的控制檯。 – meagar 2011-06-10 18:42:08