0

I'm using single table inheritance in my app and I've run into a dilemma on how to best instantiate a subclass. Say we have a class Dwelling, and subclasses Apartment and House. Now Dwelling is associated with another class Neighborhood.

models/dwelling

belongs_to :neighborhood

models/neighborhood

has_many :dwellings

Let's say I have instantiated a new neighborhood as follows and I want to create a House

n = Neighborhood.new

Which of these is the correct method?

n.dwellings.build 

House.new

If I instantiate using the first method I must fill in the dwelling :type. But with the second method I must enter the foreign key. I also read that I should never instantiate a subclass via its parent class so that would immediately rule out n.dwellings.build if this advice was correct? Any guidance would be greatly appreciated, thanks!

Steve
  • 4,446
  • 7
  • 35
  • 50

1 Answers1

0

I guess adding

has_many :apartments 
has_many :houses

along with :has_many :dwellings in Neighborhood model will solve your problem.

n = Neighborhood.new

Now you can use

n.houses.build 

or

h = House.new
n.houses << h
Krishna
  • 58
  • 7