user502052
user502052

Reputation: 15259

Examples and advices on combining a Polymorphic Association and a Single Table Inheritance

I am using Ruby on Rails 3 and I would like to know a real world example (or more) and some advice on when I should\can\must use the combination of a Polymorphic Association and a Single Table Inheritance as implemented here at the Polymorphic Association paragraph.

Upvotes: 0

Views: 582

Answers (2)

Jan Minárik
Jan Minárik

Reputation: 3267

Use STI when you need to have everything in the same object/table. Relationships to other objects, attributes and validations can change per state of the object.

Use polymorphic relationships when your object relates to another object of an unspecified type. See example by #max-williams

Upvotes: 0

Max Williams
Max Williams

Reputation: 32933

In my experience, polymorphic relationships = good and STI = PainInTheArse.

I've never seen an STI example that doesn't turn into a confusing mess.

If you have different things that have the same sort of relationship with one or more other classes then keep them as different things, with their own tables. For example, attaching documents: you might want to attach documents to lots of different kinds of things. Use a polymorphic relationship for this, called 'documentable' for example.

Document
  belongs_to :documentable, :polymorphic => true
  #expects a documentable_id field (integer) and a documentable_type field (string)

User
  has_many :documents, :as => :documentable

Company 
  has_many :documents, :as => :documentable

Upvotes: 1

Related Questions