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

4

1 回答 1

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
于 2010-05-31T18:58:16.910 回答