493: Undecipherable

-Blog-

-Projects-

-Urlaub-

-About me-

-RSS-

(Rails3) ActiveRecords: how to implement a constructor and init own attributes

Dennis Guse

Today I encountered two nasty things during Rails development. My idea was to create a generic model class (< ActiveRecord:Base) that on creation create the current timestamp. It is not possible to override initialize (at least it is doing nothing) as it is an ActiveRecord:Base.

I found the callback after_initialize defined by ActiveRecord, which is however not the correct way anymore. You should use it in macro style (source).

The next problem is that ActiveRecord overwrites the accessors and because ruby is not using the accessors by default if you are in the object, it must be called explicitely. This works for me:

1 class A < ActiveRecord::Base
2   attr_accessible :a
3   after_initialize :init
4   def init
5     @a = "a"
6     self[:a] = "b"
7   end
8 end