rails generate command provides a lot of useful functionality, however some of it may not be immediately known to you as a developer. In this article we will explore a number of useful shortcuts available in the rails model generator.
Let’s start with the basic command line usage.
rails g is the same thing as rails generate. Both commands do the same thing. We will use this shortcut throughout this article.
This command generates a model named product with 2 fields, name, which is a string, and quantity, which is an integer. By not specifying the type for name, rails defaults to using string. Below is a complete list of types that you can use with the modal generator.
Field Type Lists
You can also specify the size of a field as seen below.
This will create a name field with a limit of 100 characters. For the decimal type, you can specify a precision and scale value as well.
You can create namespaced models as well. This is useful for example, in creating a special set of administrative users that are separate from your regular users. Running the command below will place the user model in the Admin namespace, which will have a prefixed table name of admin_ in the database.
As you can see from the code listed below, the user belongs to the admin namespace like mentioned earlier.
Adding an Index
You can also add a database index right from the command line.
In addition, you can make the index unique.
You can specify a basic relationship between models.
This will create a user with a column named client_id, add an index, and automatically add a belongs_to relationship to the User model.
You can also make the relationship polymorphic.
This will set up a polymorphic relationship for pictures. Polymorphic relationships allow you to ‘share’ a table between many different models. For instance, Products and People can both have pictures.
The rails model generator exposes a lot of useful functionality that can save time if used properly. Thanks for reading!