初始化虚拟属性

时间:2010-05-31 18:54:27

标签: ruby-on-rails attributes virtual-attribute

我有一个IncomingEmail模型,其中包含attachments个虚拟属性:

class IncomingEmail < ActiveRecord::Base  
  attr_accessor :attachments
end

我希望将attachments虚拟属性初始化为[]而不是nil,以便我可以这样做:

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

首先将i.attachments设置为[](换句话说,我希望此虚拟属性默认为空数组而不是nil

1 个答案:

答案 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