How can a polymorphic object check its own class type?

I have a polymorphic class and need to know the type from within the
model (for validation).

From a controller, I can check instance[:type] to get the object’s
type, but how do I access this attribute from within the model?

If I check ‘type’, I get a warning (and wrong value). Checking
‘self.class’, just says ‘Class’.

Thanks,
Amir

helzer wrote:

Amir

Not sure I’m quite understanding this correctly but hope this helps:

class ParentKlass < ActiveRecord::Base
end

class ChildKlass < ParentKlass

def self.class_details
puts “my class is #{self}” # self here IS the class
puts “my base_class is #{self.base_class}” # gets the base class
given a class
end

def class_details
puts “my class is #{self.class}” # we’re asking for details of the
instance’s class
puts “my base_class is #{self.class.base_class}” # and then the base
class of that class
end

end

ChildKlass.class_details

my class is ChildKlass

my base_class is ParentKlass

ChildKlass.new.class_details

my class is ChildKlass

my base_class is ParentKlass

Cheers
Chris

http://www.autopendium.com
Stuff about old cars

Hi Chris,

I tried to do that, but it didn’t work for me. My mistake was, I put
that code in the parent class. So whenever this code was called, it
reported the name of the parent and not the child.

Now that I’ve moved each case to the relevant child #{self} reports
the correct class name.

And, instead of writing complex class-dependent validation in the
parent class (which is inherently wrong to do), I now have simpler
validation in each child.

Thanks,
Amir

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs