Friday, November 9, 2012

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

Today I encountered two nasty things during Rails development. My idea was to create a 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:

class A < ActiveRecord::Base
  attr_accessible :a
  after_initialize :init
  def init
    @a = "a"
    self[:a] = "b"
  end
end

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.