How to implement Active Record inheritance in Ruby on Rails?

Viewed 29458

How to implement inheritance with active records?

For example, I want a class Animal, class Dog, and class Cat.

How would the model and the database table mapping be?

4 Answers

Delegated Types

One particular way of doing this is via Delegated Types - this makes sense only if you want to paginate all animals together, and to view cats and dogs together, then the delegated type is particularly useful. I also like it because you don't need to have empty columns, for where it doesn't make sense, as is the case with Single Table Inheritance solutions.

# Schema: entries[ id, created_at, updated_at, animalable_type, animalable_id ]  

class Animal < ApplicationRecord
  delegated_type :animalable, types: %w[ Cat Dog ]
end

module Animalable
  extend ActiveSupport::Concern

  included do
    has_one :animal, as: :animalable, touch: true
  end
end

# Schema: cats[ id, selfishness_level ]
class Cat < ApplicationRecord
  include Animalable
end

# Schema: dogs[ id, favourite_game, wag_tail_level ]
class Dog < ApplicationRecord
  include Animalable
end
Related