STI, subclasses and callbacks


#1

I have a STI class tree. I want to set some default values (calculated
values so I can’t set it in the database as defaults) on every created
instance regardless of what subclass is actually instantiated. So I
figured adding a after_create callback in the top class in the hierarchy
should do the trick. It seems it doesn’t get called :frowning:

Code:
class SuperClass < ActiveRecord::Base

after_create :set_defaults

private
def set_defaults
puts “Setting defaults #{id}”
… set values …
save()
end
end

Am I doing something wrong here?

/Marcus


#2

I tried this one (that worked but it’s not very pretty…)

def SuperClass.inherited(sub_class)

sub_class.class_eval <<-EOS
after_create { |node| … set defaults … ; node.save }
EOS

end

I’m doing work in the inherited department anyway so it’s not that bad.
But I thought that callbacks should work over subclasses. Don’t they?

/Marcus


#3

On 3/1/06, marcus removed_email_address@domain.invalid wrote:

I’m doing work in the inherited department anyway so it’s not that bad.
But I thought that callbacks should work over subclasses. Don’t they?

/Marcus

It’s a slightly tricky subject, but I go over it on my blog:

http://weblog.techno-weenie.net/2006/2/21/unitialized-constant-technoweenie

Quick tips:

  • don’t override self.inherited
  • put validations/callbacks ABOVE associations (especially in Rails 1.0)


Rick O.
http://techno-weenie.net


#4

On 3/1/06, marcus removed_email_address@domain.invalid wrote:

Thanks

/Marcus

Ha, I’m sorry, wrong article. THIS one is the one i was thinking of:

http://weblog.techno-weenie.net/2006/2/15/activerecord-callbacks-and-sti

It explains the self.inherited bit.


Rick O.
http://techno-weenie.net


#5

Rick O. skrev:

It’s a slightly tricky subject, but I go over it on my blog:

http://weblog.techno-weenie.net/2006/2/21/unitialized-constant-technoweenie

How does this article relate to the subject? I see you mention STI there
but it’s in the context of Reloadable classes.

Quick tips:

  • don’t override self.inherited

Why? Is Rails doing something there as well? How do I do if I want to do
something like generate methods based on my own conventions when
subclassed (in this particular class hierarchy)?

  • put validations/callbacks ABOVE associations (especially in Rails 1.0)

Okay, I’ll try that.

Thanks

/Marcus