Refactor Steps
Locate complicated ActiveRecord queries that are repeated throughout your application. They don’t have to be identical; “similar” is a high-enough bar.
Write a single SQL query that returns a superset of the data from the queries in the previous step.
Create a database view based on that query. Be sure to choose a name that abides by ActiveRecord naming conventions. Create a view with:
create view
viewnameasquery;Create a model based on the view. Remember to carry over any associations from the base tables but omit destroy dependencies.
Within associated model classes, add associations for the new view-backed model. Again, omit destroy dependencies.
Replace the complicated ActiveRecord queries from the first step with more concise queries against the new view-backed model.
Run your tests.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access