Rails 7 adds new options to upsert_all

We often come across use cases in a Rails application where we need to create, update, or delete records in bulk. Most ORMs naively update or insert each record individually by executing N+1 database queries. To address this problem, Rails 6 added the upsert_all method that provides a faster way to update and insert a large number of records. upsert_all uses a single SQL INSERT statement for updating/inserting the records. And it does so without instantiating any models. Nor does it trigger any Active Record callbacks or validations ! How upsert_all works? If we check the

Rails Parameters Parsing and the Case of Parameters Corruption

Rails is a developer-friendly web application framework that enables developers to do more with less code, but it isn’t always clear exactly what’s going on under the covers. One area where I’ve had a hard time was understanding how Rails parses the Request query parameters and the Form variables. So what's a query parameter? Query parameters are an optional set of key-value pairs that appear after the question mark in the URL. For example, name=contra is a query parameter in https://example.com/over/there?name=contra. And what's a form variable? When we submit a

Identifying and Removing Dead Code from a Ruby on Rails Legacy Application

Dead code is code that is never executed. It can be a commented out block of code, a method that's no longer called, or an unreachable return statement. It often reflects functionality that no longer exists. Dead code has absolutely no upside and it costs us money, time, and maintenance headaches. It's possible to identify the unused block of code in smaller projects. But in larger projects, it is not as straightforward. It is a delicate process and requires absolute surety of the deadness status to avoid any unexpected breakdowns. A few tools are present that can aid us in

Identifying and avoiding Tautological tests in Ruby on Rails applications

Writing unit tests is more of an art than a skill, and understanding what to test for comes with experience and/or mistakes. We look for the percentage of test coverage for examining the health of an application. However, the "coverage percentage" might be misused or overlooked. In particular, it falls victim to Goodhart’s law, which says: “When a measure becomes a target, it ceases to be a good measure”. Whenever we start writing test cases for the sake of improving the code coverage, we miss the whole point of testing and rather introduce Tautological Tests - poorly designed