开发者

Initialize virtual attributes

开发者 https://www.devze.com 2023-01-01 22:44 出处:网络
I have an IncomingEmail model with an attachments virtual attr开发者_开发知识库ibute: class IncomingEmail < ActiveRecord::Base

I have an IncomingEmail model with an attachments virtual attr开发者_开发知识库ibute:

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)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号