Rails Generator (AKA Rails Magic).

A couple weeks ago I was introduce to the concept of Magic in Rails, at the beginning, like most people, I was skeptical about the myths about what it could do. This popular framework in fact allows you to create a web application in a few hours from scratch but, again, the idea that some piece of code could do so much is like something from a children’s book of wizards and alchemists.

Rails magic refers to a broad set of instructions deep in the Ruby on Rails code that facilitates the creation of files, relations between tables in the data base, security, forms and tags for views, and much more functionality (honestly I only have learned a fractions of Rails’ power) to help you implement your designs. All of this happens under Rails’ hood and most of the time we don’t have a clue of what’s going on, but it definitely make our lives easier.

In this section I will be talking about Rails Generator and how to create some basic functionality using MVC design architecture.

  1. Models

Creating Models using rails g command in your shell (g is an abbreviation for generate) follows this type of syntax:

rails g model <model_name> <column_1>:data_type <column_2>:data_type:option

An example would be:

rails g model User first_name:string{40} last_name:string{40} age:integer email:string:uniq

Looking at this expression, we can understand the following:
We are calling the rails generate routine for models, capitalizing the tables’ name for conventions, and then proceeding to add columns and data types, separated by colons. Also, we can give special attributes to the columns; this will be covered with more depth in the data type section.

This action will generate these files:

create db/migrate/20181103175426_create_users.rb
create app/models/user.rb

The content of the migration file:

class CreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
t.string :first_name, limit: 40
t.string :last_name, limit: 40
t.integer :age
t.string :email
add_index :users, :email, unique: true

2. Data types and Options

The following is a list with data types and a short explanation. These posts were the inspiration for this article: https://richonrails.com/articles/rails-model-generator-shortcuts , https://medium.com/@kevinyckim33/rails-generators-cli-cheatsheet-711295e7a1ed and , https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/model/USAGE.

:string for small text.

:text for paragraph. Big text


:decimal{15,2}, (float also can be use) for decimal values, the two attributes are length and precision.

:boolean values only true and false (some databases will set this value to 0 or 1)

:date date object

:timestamp this will create the column create_at and updated_at to the database

:binary allow to store media files (images, videos, songs).

Some options for columns:

:uniq creates a validation for the column were every row must have unique content

:reference creates a reference with a column in a table that was already created, (belongs to)

{int} limits the amount of characters in the row

:index indexes the particular column

Some options of Models generator:

— parent: this will create a child relationship of the new class with parent

rails g model Admin name:string password:digest — parent User

This will generate:

class Admin < User

— no-test-framework it won’t create the test files if you have a test gem installed

3. Migrations

It will help to generate migrations to modify your existing tables:

To add a column to the User table:

rails g migration AddColumnAddressToUser address:string

This will generate the migration file with the following content:

class AddColumnAddressToUser < ActiveRecord::Migration[
def change
add_column :users, :address, :string

To delete a column:

rails g migration RemoveColumnAddressFromUser address

The migration file will look something like this:

class RemoveColumnAddressFromUser < ActiveRecord::Migration
def change
remove_column :users, :address, :string

Rails generator gives us ways to rename columns, but the fact is the generator will create the migration files with a minimum amount of information and we need to write the migrations by hand. The syntax is:

rails g migration RenameUserFirstNameToName

But this is only going to generate:

class RenameUserFirstNameToName < ActiveRecord::Migration
def change

And you will need to populate the change method by hand.

This happens in a similar fashion with changing the column type. The syntax is:

rails g migration ChangeUserLastName

And don forget to run the migrations using the command:

rake db:migrate

4. Controllers

The syntax for creating new controller is:

rails g controller Order index show update

This will generate a controller file, the views, tests and routes. The attributes added will populate your controller file with the actions, create routes to these attributes and create particular views for them.

create  app/controllers/order_controller.rb
route  get 'order/update'
route  get 'order/show'
route  get 'order/index'
create    app/views/order
create    app/views/order/index.html.erb
create    app/views/order/show.html.erb
create    app/views/order/update.html.erb

Rails will hand roll the recently create route and you can see it in the routes file

Rails.application.routes.draw do
get 'order/index'
  get 'order/show'
  get 'order/update'

The controller file:

class OrderController < ApplicationController
def index
  def show
  def update

Rails also create the views for the controller and the attributes, this will live in the “app/views/order/” folder

5. Resources

The syntax for creating resources is:

rails g resource Item name:string description:string price:float inventory:integer

If more attributes are added, this will create model, migration, controllers, views, routes and test files, but this won’t force the creation if the files exist.

Be aware, resource generator will create more files then you may need.

These will be some of the files generated:

create    db/migrate/20181107175930_create_items.rb
create    app/models/item.rb
create    app/controllers/items_controller.rb
create    app/views/items
route    resources :items

In the case that the resource didn’t exist, you will get:


class Item < ApplicationRecord


class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.string :name
t.string :description
t.float :price
t.integer :inventory


class ItemsController < ApplicationController


Rails.application.routes.draw do
resources :items