2010-05-31 173 views
2

我有一個IncomingEmail模型與attachments虛擬屬性:初始化虛擬屬性

class IncomingEmail < ActiveRecord::Base 
    attr_accessor :attachments 
end 

我想attachments虛擬屬性初始化爲[]而不是nil,這樣我可以這樣做:

>> i = IncomingEmail.new 
=> #<IncomingEmail id: nil,...) 
>> i.attachments << "whatever" 

沒有先設置i.attachments[](換句話說,我想這個虛擬屬性默認爲一個空數組而不是nil

回答

3

使用after_initialize回調

class IncomingEmail < ActiveRecord::Base 
    attr_accessor :attachments 
    def after_initialize 
    self.attachments ||= [] # just in case the :attachments were passed to .new 
    end 
end 
+0

是,並沒有覆蓋ActiveRecord的默認初始值 – allenwei 2010-06-01 01:26:11