D-Rock
D-Rock

Reputation: 2676

ActiveRecord Multi Level Single Table Inheritance Query

I am trying to use Single Table Inheritance to query for all records within a class hierarchy from a class that is not the base class for the single table inheritance. For example, given the following class heirarchy.

class Animal < ActiveRecord::Base; end

class Dog < Animal; end

class Mutt < Dog; end

class PureBred < Dog; end

I want to be able to query for all of the dogs

dogs = Dog.all

and dogs be a list of instances of Mutt and PureBred.

Can this be done? I tried a proof of concept by setting the default_scope in the Dog class to

default_scope { where(:type => ['Mutt', 'PureBred']) }

but ActiveRecord is still appending the more restrictive condition of WHERE type IN ('Dog')

Upvotes: 3

Views: 971

Answers (1)

user229044
user229044

Reputation: 239291

No; you're running up against a technical limitation of Rails' implementation of STI.

You'll have to query the base class:

Animal.where(type: %w(Dog Mutt PureBred))

Upvotes: 4

Related Questions