Model Generator of Rails

Origin

Basic Usage

1
rails g model User email

This command will generate user model with email field type of string, migration which creates user table, test for model and factory.

If you want to have model with different type of string pass type after field name following by :.

The whole list of available types:

1
2
3
4
5
6
7
8
9
10
11
12
integer
primary_key
decimal
float
boolean
binary
string
text
date
time
datetime
timestamp

You are able to pass -option parameter to generator. It will inherit generating class from passed name to achieve STI(Single Table Inheritance):

1
rails g model admin --parent user

This example generates model:

1
2
class Admin < User
end

Interesting fact that if you generate model in some scope passing model like admin/user of Admin::User:

1
rails g model admin/user

you will get generated model in scope app/models/admin/user.rb, defined scope app/models/admin.rb which is required to define module.

1
2
3
4
5
module Admin
def self.table_name_prefix
'admin_'
end
end

It means that generated table name for Admin::User starts with prefix _admin_user_. This feature allows to have seperated namespaced models as in rails code as in db schema.

Advantage useage

Sometimes you have to automatically add index for columns in your migration. It’s not a problem.

1
rails g model user email:index location_id:integer:index

Or uniq index

1
rails g model user pseudo:string:uniq

Set limit for field of integer, string, text and binary fields

1
rails g model product 'price:decimal{10,2}'

The last useful feature of generators - it’s options to generate reference columns (fields which are used in rails as foreign_key)

1
rails g model photo album:references

This command will generate photos table with integer field _album_id_ and also it will add index for this field automatically.

1
2
3
4
5
6
7
8
9
10
11
class CreatePhotos < ActiveRecord::Migration
def change
create_table :photos do |t|
t.references :album

t.timestamps
end

add_index :photos, :album_id
end
end
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×