Jeremiah
Jeremiah

Reputation: 106

Ruby on Rails has_many polymorphic

I have a model, Item.
Each Item has_many traits.
The traits can be many different things:
A SizeTrait
A ToppingsTrait
A FlavorTrait
etc

How can I set up this relationship in Ruby on Rails? In a normal Ruby app I could just use duck typing, but this needs to be stored the the database.

It's like the reverse of belongs_to with polymorphic: true

I would like to avoid single table inheritance as these traits, while they will share a duck type interface, will have very different functionality. This would cause a lot of unused fields in the table and that seems like a messy, confusing way of doing it.

There are a couple posts about this already on StackOverflow, but one has a different situation than mine and the other has a pretty dodgy solution, and I want to see if there's a better one.

Upvotes: 2

Views: 175

Answers (1)

ilan berci
ilan berci

Reputation: 3881

You can't make joins across a polymorphic association. The best approach is to just buckle down with the STI as you mentioned previously. Although you may argue that you will have multiple fields witch will be null, at least rails will be able to make sensible joins to aid you in your queries.

Upvotes: 1

Related Questions