# Not-Null Shortcut in Rails 8 Migration Generator

*Published on October 07, 2024*

---


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.

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

It will produce the following migration.

```ruby
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.**&nbsp;While reading the corresponding&nbsp;[pull request from DHH](https://github.com/rails/rails/pull/52327/files), I came across the&nbsp;[`starts_ends_with.rb`](https://github.com/rails/rails/blob/main/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb)&nbsp;core extension, which simply extends the String class by aliasing&nbsp;`starts_with?`&nbsp;and&nbsp;`ends_with?`&nbsp;to Ruby's built-in&nbsp;`start_with?`&nbsp;and&nbsp;`end_with?`&nbsp;methods, which always felt a bit awkward to me while reading.

```ruby
# 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:**&nbsp;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.

```ruby
# 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&nbsp;[Extract Variable](https://refactoring.com/catalog/extractVariable.html)&nbsp;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)](/notes-on-refactoring)

