Ruby on Rails Model Generator Useful Shortcuts

Ruby on Rails Renaming a Database Column

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 model User

rails g is the same thing as rails generate. Both commands do the same thing. We will use this shortcut throughout this article.

1
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.

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
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.

1
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.

1
rails g model admin/user

As you can see from the code listed below, the user belongs to the admin namespace like mentioned earlier.

app/models/admin/user.rb
1
2
class Admin::User < ActiveRecord::Base
end

Adding an Index
You can also add a database index right from the command line.

1
rails g model Site name:string:index

In addition, you can make the index unique.

1
rails g model Client name:string:uniq

Model Relationships

You can specify a basic relationship between models.

1
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.

1
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!