Rails 7 generators will raise errors if an attribute type is invalid


Rails is known for its Convention over Configuration and its Omakase principles which is meant for programmer happiness by not burdening them with a lot of options/configurations. Rails provides a lot of generators to support that principle. We’ve all used generators to create models and resources at least once in our Rails app. Similarly, we’ve also made mistakes generating resources where our types become our attributes and attributes become our types.

Let us take a look at one of many common mistakes we have all made while generating a resource/model:

  rails generate scaffold Person name:string phone:number

This generates the following migration:

  class CreatePeople < ActiveRecord::Migration[6.1]
    def change
      create_table :people do |t|
        t.string :name
        t.number :phone

        t.timestamps
      end
    end
  end

The problem with the above migration is that number is not a valid type, even though it did not raise any errors, which may lead us to think that everything worked well. Only when we run the migration will we find out the problem.

However, this will not be a problem anymore since Rails 7 generators will raise an error for invalid types.

Let’s take another common mistake Rails programmers make while generating migration to understand how this will work.

Let us assume we want to scaffold a Book resource with name as a string and an author association. However, while writing the generator we got confused between reference and references and decided to go with reference.

  rails generate scaffold Book name:string author:reference

Before

Rails will assume the type for author now as reference and generate the following migration:

  class CreateBooks < ActiveRecord::Migration[6.1]
    def change
      create_table :books do |t|
        t.string :name
        t.reference :author

        t.timestamps
      end
    end
  end

This will result in an error as there is no type called reference. (It should have been references.)

After

However, in Rails 7, the application will check all attributes for valid migration types and, it will raise Rails::Generators::Error before creating the migration. Validation is done by checking the default migration types and database adapter’s valid_types.

Our migration command will produce the following error:

  rails generate scaffold Book name:string author:reference
  Could not generate field 'author' with unknown type 'reference'.

This is a great enhancement as it makes generating resources/models easier and efficient as we don’t have to worry if we have mistakenly entered the wrong data types.