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’.


helzer wrote:


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

class ParentKlass < ActiveRecord::Base

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

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



my class is ChildKlass

my base_class is ParentKlass

my class is ChildKlass

my base_class is ParentKlass

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.


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