How to denormalize and represent an associated record on the same table

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.

Last Updated: 2022-12-01

Let's say you want to denormalize your database for speed reasons and represent a user's subscription (of which it has either 0 or 1 of) on the users table (as opposed to on a separate 'subscriptions' table, as is more typical).

You could do this by putting the subscription related columns (e.g. subscription_type and subscription_id) on the users table and then in your backend code add a method to User called subscription using that data:

Subscription.new(subscription_id, subscription_type)

In the Rails world, you can use composed_of to automatically instantiate this connection object

# The second value in each mapping tuple is how the data gets called in the value object this produces
composed_of :subscription, mapping: [ %w(subscription_type subscription_type), %w(subscription_id id) ]

Resources