I am a Sr. Software Developer at Oracle Cloud. The opinions expressed here are my own and not necessarily those of my employer.
Polymorphic relation to Single Table Inhertiance records
Previously I have written about single table inheritance and polymorphic relations. Here is an interesting combination of the two.
Let’s start with a simple belongs_to
and has_many
relationship with Mongoid
Here is a more complex polymorphic relationship.
Now we introduce single table inheritance to store admin
users.
When Admin writes an Article data is stored like this:
Now we decide to get rid of Admin model and just have User model. We create a migration to change User records by removing _type
attribute.
But what about our Article records? We need to update them too.
Otherwise we will get uninitialized constant Admin
when trying to load articles with those relations.
Finally we decided to consolidate Company and User models and no longer use polymorphic relationship to author
from Article. With Mongoid we can manually specify IDs during creation so we do not need to change the author_id
. Here is the migration:
If we were not able to manually specify User.id
to be the same as Company.id
we would need to this:
Here is a link to Rails documentation.