Today I Learned

hashrocket A Hashrocket project

Generate non-null field migration in Rails 8

I'm sure many of us are familiar with the Ruby on Rails migration generator...

rails generate migration add_name_to_widgets name

which generates a migration that looks like so:

class AddNameToWidgets < ActiveRecord::Migration[7.0]
  def change
    add_column :widgets, :name, :string
  end
end

Then to make the name column have a non-null constraint an addition of null: false would be needed:

class AddNameToWidgets < ActiveRecord::Migration[7.0]
  def change
    add_column :widgets, :name, :string, null: false
  end
end

However, now in Rails 8 an adjustment was made to allow this to be done from the generator shorthand

rails generate migration add_name_to_widgets name:string!

By adding the exclamation point after the column type a migration will now be generated as we wanted before but without the additional manual edit:

class AddNameToWidgets < ActiveRecord::Migration[8.0]
  def change
    add_column :widgets, :name, :string, null: false
  end
end

h/t Akshay Khot

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.