2

I'm working on a hobby project and have an abstract Event model with STI subclasses Meal, Outing, Medication, etc. The Event parent model has start_time, end_time, description, etc.

I want to have nested resources for the various subclasses. For example, I want to be able to attach multiple instances of the Image class to any Event subclass. I want to be able to attach multiple instances of the Medicine class to the Medication entities, multiple instance of Location to Outing, etc.

My reason for considering polymorphism is to provide flexibility so that, conceivably, any of the different types of nested resources could be attached to any of the subclasses of Event. This would allow somebody to attach a medicine of "Vitamin D Supplement" to a Meal, for example.

My questions are:

  1. Should the nested resources be polymorphic?
  2. If I make them polymorphic, will all of the instances contain Event in the type table?
  3. If so, should I just make them has_many relationships?
  4. Is there any performance advantage to making them has_many vs. polymorphic?
Clay
  • 2,949
  • 3
  • 38
  • 54

1 Answers1

0

(1) Yes.

(2) Yes, depending on how you handle the polymorphism. Rails allows for STI (single table inheritance) so all subtypes of event can inherit the has_many relation. The related has_many record can have many subtypes, and all of these will appear as relations when called.

(3) has_many can be used in conjunction to polymorphic, they are not mutually exclusive.

(4) Again, the two are not mutually exclusive. In fact, polymorphic is needed on your belongs_to relation. Your related record should include a relation_id and relation_type in its table. If you are using STI, for instance, you would do it like this:

class BaseClass < ActiveRecord::Base
  has_many :foo
end

class SubClass < BaseClass
  # inherits has_many :foo relation from BaseClass
end

class Foo < ActiveRecord::Base
  belongs_to :base_class, polymorphic: true
end

class Bar < Foo
  # inherits belongs_to :base_class from Foo
end

When calling sub_class-instance.foos, you should get an ActiveRecord relation of all foos, including subtypes.

Eddie Prislac
  • 145
  • 1
  • 10