0

How can I have 2 different references columns in 2 models which inherit from a common class using single table inheritance?

I have found this Single Table Inheritance (STI) column associations answer but as it is 10 years ago is there a better solution now in rails?

Problem example: I want something like Consider classes (Animal has type to identify the Lion/Human)

class Animal < ApplicationRecord
    belongs_to :classA
end

class Lion < Animal
    belongs_to :two_legged
end

class Human < Animal
    belongs_to :four_legged
end

So finally I want Lion to belong to classA and two_legged; Human to belong to classA and four_legged

Is there any other better solution than to define all three belongs_to in Animal and making unrelated column nil in Lion & Human ??

ray
  • 5,454
  • 1
  • 18
  • 40
Rahul
  • 23
  • 3

1 Answers1

0

Follow the official doc:

class Animal < ApplicationRecord
    belongs_to :classA
    has_many :lions
    has_many :humans
end

class Lion < ApplicationRecord
    belongs_to :animal
end

class Human < ApplicationRecord
    belongs_to :animal
end
michaelrbock
  • 1,160
  • 1
  • 11
  • 20