(Rails3) ActiveRecords: how to implement a constructor and init own attributes
Dennis GuseToday 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
2
3
4
5
6
7
8
class A < ActiveRecord::Base
attr_accessible :a
after_initialize :init
def init
@a = "a"
self[:a] = "b"
end
end