How my team redefined the way we store one of the polymorphic associations in the Shopify codebase. This post is the solution we wish we found when we were looking.
Overview
This article discusses how the Payment Flexibility team at Shopify redefined the storage of polymorphic associations in Rails by transitioning from storing class names to arbitrary strings. This change aimed to reduce coupling between the codebase and the database, facilitating easier future modifications.
What You'll Learn
How to redefine polymorphic associations in Rails to use arbitrary strings instead of class names
Why reducing coupling between your codebase and database can simplify future changes
When to consider changing how polymorphic types are stored in your application
Prerequisites & Requirements
- Basic understanding of Rails polymorphic associations
- Familiarity with Active Record and database migrations(optional)
Key Questions Answered
How can you change the way Rails stores polymorphic associations?
What are the benefits of not storing class names as polymorphic types?
What issues arise when changing namespaces in Rails polymorphic associations?
When should you consider implementing arbitrary strings for polymorphic types?
Technologies & Tools
Some links below are affiliate links. We may earn a commission if you make a purchase.
Key Actionable Insights
1Consider redefining polymorphic associations to use arbitrary strings to enhance flexibility.This approach allows for easier renaming and restructuring of classes without impacting existing database records, which can save time and reduce errors during future development.
2Implement a strategy for cleaning up your database after transitioning to arbitrary strings.Once you switch to using arbitrary strings, run migrations or scripts to ensure that all records reflect the new format. This will help maintain consistency and prevent confusion in your application.
3Regularly review your database schema and associations to ensure they align with your current codebase structure.This practice helps identify potential issues early, especially when making significant changes to your application's architecture.