views:

55

answers:

1

I have the following scenario

class XYZ < ActiveRecord::Base
has_many :abcs
end

class ABC < ActiveRecord::Base
belongs_to :xyz
end

class A < ABC
end

class B < ABC
end

class C < ABC
end

The model ABC doesn't have any controller, or view. Data related to ABC will be inserted from the XYZ views and controllers. The user sets a type value for ABC which might be either A, B or C.

And as per the type the corresponding STI subclass must be instantiated and the data must be saved appropriately. But here the subclasses are not getting instantiated, the data is getting saved perfectly. But I am doing it the wrong way as I have written the code of the subclasses into the parent STI class because that code was not getting called in the subclass.

Please give suggesstions and provide some solutions or tutorials.

Thanx in advance.

A: 

Make sure the ABC model has a type attribute, and that it is being set correctly to either "A", "B", or "C" when you save instances of these classes.

ABC.find and friends should then return instances of the respective class.

When creating new objects, you will of course need some code in your controller to call new on the correct subclass depending on some input parameter.

Lars Haugseth
I do have a type column where the type is being set. I am just not getting how do I run the custom code which is present inside the child STI classes. Please show the way to execute that part of code which is present in the child STI classes.
Rohit
@Rohit: What kind of code? Class methods, instance methods, or code within the class definition? How and from where do you call that code? You will have to provide some examples.
Lars Haugseth
Those are instance methods which are present in the child STI classes.
Rohit