RailsUJS vs. Mrujs vs. Request.js

Rails 7 officially removed including rails-ujs by default. So does that mean we should stop using rails-ujs then? And what are Mrujs and Request.js? In this quick post, I answer those questions. Let's start with a quick summary of what rails-ujs all about: rails-ujs is a rewrite of the…

Active Record includes and N + 1 Query Problem

Consider the following code books = Book.limit(10) books.each do |book| puts book.author.last_name end In the above code, a query is made each time the lastname of an author of a book is needed in puts book.author.last_name. A single query for each book.…

How to Use Enums in Rails Active Record

Suppose you're making a book tracking app to keep a log of all the books you consume. And you want to log the format. As in, was it an ebook, an audiobook or was it an actual physical paper copy? You would create a column named format on your model.…

Rails Console Commands Cheatsheet

Rails console is a useful playground for trying out various view helper commands as well as experimenting with our ActiveRecord data model. Here is a rundown of some things we can do in a Rails console session. Basic commands Reloading the Console We can enter the Rails console by typing…

Active Record Association Advanced Topics

What are polymorphic associations? When do we need to create join tables? When do we use single table inheritence? We will cover some more advanced topics with Active Record Associations in this post. Note: This post assumes that you are already familiar with common Active Record associations. You can see…

Rails Active Record Association Basics

In Rails, an association is a connection between two Active Record models. With associations we get convenient utility methods to easily query and do operations on those models. Rails has the following associations belongs_to, has_many, has_one, has_one :through, has_many :through, has_and_belongs_to_many…

What is Arel: Between ActiveRecord and SQL Queries

I recently learned that ActiveRecord uses Arel under the hood. What is Arel? When would it be useful in practice? let's find out! Motivation ActiveRecord is useful and its DSL allows us to write many queries with .find_by and .where. But it does have limitations in the types of…

Stimulus Rails 7 Tutorial

Hotwire (HTML-over-the-wire) ships by default in Rails 7. Stimulus is one component of Hotwire, the other one being Turbo. The key promise of the Hotwire approach is to get the benefits of single-page JavaScript applications like faster, more fluid user interfaces without writing much Javascript (certaintly not the amount needed…