Tom Lehman
Tom Lehman

Reputation: 89203

Initialize virtual attributes

I have an IncomingEmail model with an attachments virtual attribute:

class IncomingEmail < ActiveRecord::Base  
  attr_accessor :attachments
end

I want the attachments virtual attribute to be initialized to [] rather than nil so that I can do:

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

Without first setting i.attachments to [] (put another way, I want this virtual attribute to default to an empty array rather than nil)

Upvotes: 3

Views: 1274

Answers (1)

Eimantas
Eimantas

Reputation: 49354

use after_initialize callback

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

Upvotes: 3

Related Questions