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.
Basics
Let’s start with the basic command line usage.
1
|
|
rails g
is the same thing as rails generate. Both commands do the same thing. We will use this shortcut throughout this article.
1
|
|
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
- integer
- primary_key
- decimal
- float
- boolean
- binary
- string
- text
- date
- time
- datetime
- timestamp
You can also specify the size of a field as seen below.
1
|
|
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.
1
|
|
Namespaced Models
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.
1
|
|
As you can see from the code listed below, the user belongs to the admin namespace like mentioned earlier.
1 2 |
|
Adding an Index
You can also add a database index right from the command line.
1
|
|
In addition, you can make the index unique.
1
|
|
Model Relationships
You can specify a basic relationship between models.
1
|
|
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.
1
|
|
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!