我有一个IncomingEmail
模型,其中包含attachments
个虚拟属性:
class IncomingEmail < ActiveRecord::Base
attr_accessor :attachments
end
我希望将attachments
虚拟属性初始化为[]
而不是nil
,以便我可以这样做:
>> i = IncomingEmail.new
=> #<IncomingEmail id: nil,...)
>> i.attachments << "whatever"
首先将i.attachments
设置为[]
(换句话说,我希望此虚拟属性默认为空数组而不是nil
)
答案 0 :(得分: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