Search code examples
ruby-on-railsrubyinheritancesingle-table-inheritance

How to return children objects?


I have -- what I think -- is a simple question. Here's my code:

class Fruit < ActiveRecord::Base
end

class Apple < Fruit
end

class Kiwi < Fruit
end

Assume that I have all the STI setup correctly, and there are multiple types of Apple and Kiwi records in the table. From here...

fruits = Fruit.find(:all)

...how do I return an array of just Apples from the fruits array?


Solution

  • The same way you would do it if they were just normal objects:

    fruits.select {|fruit| fruit.is_a?(Apple) }
    

    STI uses the type field to keep track of the submodel, so you could also do

    fruits.select {|fruit| fruit.type == "Apple" }
    

    If you want to get only the apples from the database, just do

    Apple.find(:all)