Passing Modifiers :: rails generate migration

2.3 Passing Modifiers

Some commonly used type modifiers can be passed directly on the command line. They are enclosed by curly braces and follow the field type:

For instance, running:

$ bin/rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}

will produce a migration that looks like this

class AddDetailsToProducts < ActiveRecord::Migration
  def change
    add_column :products, :price, :decimal, precision: 5, scale: 2
    add_reference :products, :supplier, polymorphic: true, index: true

Have a look at the generators help output for further details.

Advanced usage

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

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

Or uniq index:

$ rails g model user pseudo:string:uniq

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

$ rails generate model user pseudo:string{30}

Special syntax to generate decimal field with scale and precision:

$ rails generate model product 'price:decimal{10,2}'

Pay attention that you have to wrap parameter price:decimal{10,2} to quotes. It’s vital and you may have incorrect behavior of generator if you don’t do it. Full explanation of this case is here.

You can combine any single curly brace option with the index options:

$ rails generate model user username:string{30}:uniq

And the last useful feature of generators – it’s options to generate reference columns (fields which are used in rails as foreign keys):

$ rails generate 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. Make sure in it by looking at generated migration:

class CreatePhotos < ActiveRecord::Migration
  def change
    create_table :photos do |t|
      t.references :album

    add_index :photos, :album_id

For polymorphic reference use this syntax:

$ rails generate model product supplier:references{polymorphic}

Polymorphic reference with indexes:

$ rails generate model product supplier:references{polymorphic}:index


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s