Rails provides great Query Logs detailing exact database queries made. It looks something like this,
However, when debugging for slow or troublesome queries, we might need extra information. Instead of polluting the codebase with multiple print statements, it’s a great idea to add the Marginalia gem by Basecamp. Now, this is how the query logs would look,
In Rails 7
A recent PR to Rails brings Marginalia SQL comments to Rails as a native feature! It’s a much welcome change.
This PR allows for configurable tags that can be automatically added to all SQL queries generated by Active Record.
To turn this feature on, simply set a config option,
By default the application, controller and action details are added to the query tags:
We can also configure our tags using procs.
Custom tags containing static values and procs can be defined in the application configuration:
You can define both static values like
app_version or dynamic values like
Dynamic values are resolved with context inside the respective controller.
There are many more configurations possible, we suggest reading the PR before implementation!