Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Initialize Extra Attributes In Activerecord-classes

DZone's Guide to

Initialize Extra Attributes In Activerecord-classes

·
Free Resource
Classes derived from ActiveRecord::Base don't call initialize on creation. 
Extra attributes (i.e. non DB-attributes) can be initialized with the after_initialize callback.

class Something < ActiveRecord::Base 
  attr_reader :extra_attribute

  def after_initialize
    @extra_attribute = 'default_value'
  end

References:
- http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html
- http://blog.hasmanythrough.com/2007/1/22/using-faux-accessors-to-initialize-values
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}