Not-Null Shortcut in Rails 8 Migration Generator

Not-Null Shortcut in Rails 8 Migration Generator

October 07, 2024

Rails 8 lets you mark a database column as not-null by appending an exclamation mark after the column while generating a migration. It's a nice quality of life improvement. This post also contains a few things I learned after reading the pull request.

If you're on the latest (8) version of Ruby on Rails, there's a nice shortcut to add the not null modifier to your database columns. Just add an exclamation mark after the type, and Rails will mark that column as not null.

For example, consider the following generator command.

$ bin/rails generate migration CreateUsers email_address:string!:uniq password_digest:string!

It will produce the following migration.

class CreateUsers < ActiveRecord::Migration[8.0]
def change
create_table :users do |t|
t.string :email_address, null: false
t.string :password_digest, null: false

t.timestamps
end

add_index :users, :email_address, unique: true
end
end

Pretty handy!

P.S. While reading the corresponding pull request from DHH, I came across the starts_ends_with.rb core extension, which simply extends the String class by aliasing starts_with? and ends_with? to Ruby's built-in start_with? and end_with? methods, which always felt a bit awkward to me while reading.

# frozen_string_literal: true

class String
alias :starts_with? :start_with?
alias :ends_with? :end_with?
end

Love the lengths Rails will go to make the code read like prose.

One more thing: I also liked how he used intermediate variables to clearly show what the method is returning. The first version doesn't immediately tell you the type of returned values, whereas the second option makes it obvious.

# From
return $1, size: $2.to_sym

# To
parsed_type, parsed_options = $1, { size: $2.to_sym }
...
...
return parsed_type, parsed_options

A nice illustration of Martin Fowler's Extract Variable refactoring. Check out my notes on Refactoring to learn more. Highly recommend reading this book.

Refactoring: Improving the Design of Existing Code (My Notes and Highlights)

Sign up for my newsletter

Let's learn to become better developers.

Comments

No comments yet. Be the first to leave one.

Sign in to leave a comment.