This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.
Last Updated: 2024-11-23
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) ]