DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Initialize Extra Attributes In Activerecord-classes

11.30.2009
| 5087 views |
  • submit to reddit
        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