0

I have used Single Table Inheritance (STI) to create some Models with subclassed from a common parent. A separate model has an association with the superclass. Eg: as follows...

class Fruit < ActiveRecord::Base
  has_many :smoothies
end

class Apple < Fruit
end

class Banana < Fruit
end

class Smoothie < ActiveRecord::Base
  belongs_to :fruit
end

Is there any way to query for a certain subclass without manually creating a method for each subclass?

I would like to be able to do something along the lines of my_smoothie.apple to get an Apple instance if my_smoothie is associated with an Apple

Update

My use case is actually where I have a relation of Smoothies and I want to do some_smoothies.apples to get a relation containing any associated Apples.

tereško
  • 58,060
  • 25
  • 98
  • 150
Felix
  • 674
  • 5
  • 16

2 Answers2

0

If you do a my_smoothie.fruit, you should get back an Apple object (not a Fruit object, Rails magic). You may be good as is.

Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70
  • Thanks @Swards - This doesn't entirely solve my problem. I have updated the question to better reflect what I'm trying to achieve. – Felix Jan 10 '13 at 12:30
0

could you do this?

my_smoothie.fruit.where(type: "Apple")

Of course if you need to dynamically infer the name of your subclasses you could use

subclass_object.class.to_s # if you have an instantiated object e.g. of 'apple'
subclass.to_s # if you start form the subclass e.g. of Apple

And if this is ok for you, consider creating named scopes for it