...

/

Iteratively Writing Migration Code to Create the Correct Schema

Iteratively Writing Migration Code to Create the Correct Schema

Learn how to iteratively write migration code for the correct schema of the database for our Rails application.

We'll cover the following...

We’ll need to work a bit backward. We can’t create widgets first, because it must reference widget_statuses and manufacturers. The manufacturers must reference addresses. So, we’ll start with widget_statuses. By default, Rails creates nullable fields. We don’t want that. Fields with required values should not allow null. We’ll use null: false for these fields (even for nullable fields we like to use null: true to make it clear that we’ve thought through the nullability).

We also like to document tables and columns using comment:. This puts the comments in the database itself to be viewed later. Even for something that seems obvious, we will write a comment because we’ve learned that things are never as obvious as they might seem.

Press + to interact
# db/migrate/20210101000000_make_widget_and_manufacturers.rb
class MakeWidgetAndManufacturers < ActiveRecord::Migration[7.…
def change
→ create_table :widget_statuses,
→ comment: "List of definitive widget statuses" do |t|
→ t.text :name, null: false,
→ comment: "The name of the status"
→ t.timestamps null: false
→ end
→ add_index :widget_statuses, :name, unique: true,
→ comment: "No two widget statuses should have the same name"
end
end

Note that we’ve created a unique index on the :name field. Although database indexes are mostly for allowing fast querying of certain fields, they are also the mechanism by which databases enforce uniqueness. Thus, to prevent having more than one status with the same name, we create this index, specifying index: { unique: true }.

This will create a case-sensitive constraint, meaning the statuses Fresh and ...