Rails Model Generator Shortcuts
This article will show you several shortcuts you can use when calling the rails generate model command.
Published on:October 13, 2013
The 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.
The Basics
Let's start with the basic command line usage.
rails g model User
the rails g
is the same thing as rails generate
. Both commands do the same thing. We will use this shortcut throughout this article.
rails g model Product name quantity:integer
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.
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.
rails g model Client name:string{100}
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. Make sure you place these field settings in quotes like so:
rails g model Product name 'price:decimal{12,2}'
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.
rails g model admin/user
As you can see from the code listed below, the user belongs to the admin namespace like mentioned earlier.
class Admin::User < ActiveRecord::Base
end
Adding an Index
You can also add a database index right from the command line.
rails g model Site name:string:index
In addition, you can make the index unique.
rails g model Client name:string:uniq
Model Relationships
You can specify a basic relationship between models.
rails g model User client:references
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.
rails g model picture imageable:references{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!