Rails 8 not-null modifier in migration generator

Not-Null Shortcut in Rails 8 Migration Generator

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.

2 min read

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)
I recently re-read Martin Fowler’s excellent book on refactoring. It’s about improving the design and quality of your code in small steps, without changing external behavior. The book contains detailed descriptions of refactorings, with motivation, mechanics, and an example for each. A must-read.

That's a wrap. I hope you found this article helpful and you learned something new.

As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. I reply to all emails I get from developers, and I look forward to hearing from you.

If you'd like to receive future articles directly in your email, please subscribe to my blog. Your email is respected, never shared, rented, sold or spammed. If you're already a subscriber, thank you.