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:
This generates the following migration:
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
while writing the generator we got confused between
references and decided to go with
Rails will assume the type for
author now as
reference and generate the following migration:
This will result in an error as there is no type called
reference. (It should have been
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:
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.