DEV Community

Kevin Downs
Kevin Downs

Posted on

Rails Reference

Recently I was trying to decide on a new personal project to work on to keep my skills sharp after graduating from Flatiron School. I had just been 2 months deep in learning JavaScript and Reactjs, and realized that I hadn't even looked at Ruby and Rails in quite some time. I decided that I really should brush up on those skills and so my next project would be a Rails one.

I opened up my VSCode, went to start my new project, and then realized that although I knew what needed to be done I had forgotten a lot of simple commands and syntax to get started. I decided this has to be something that happens to other developers as well, and so as a refresher and future reference for myself and others, I thought it might be a good idea to compile a list of commonly used rails tidbits. A cheat sheet, if you will.

Command Line Basics

Creating a new project

rails new my_app

There are a number of flags that can be included after your project name in the rails new command as well as with other rails commands.

-B [--skip-bundle]          #Do no run bundle install
-G [--skip-git]             #Skip .gitignore file
[--skip-gemfile]            #Don't create a Gemfile
-d [--database=DATABASE]    #Preconfigure for selected database
                            #(options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/s)
-T [--skip-test-unit]       #Skip Test::Unit files
-f [--force]                #Overwrite files that already exist
-h [--help]                 #Show help message and quit

The rails server command launches a server that allows you access to the application through a web browser.

rails server  #or  rails s
-p [desired port]          #Flag for changing server port
-e [desired environment]   #Flag for changing environment

Rail console launches an IRB session in the command line.

rails console   #or   rails c
-e         #Flag specifying environment the console should operate
--sandbox  #Flag that allows testing code without changing data

Routes

The rails routes command will show you a list off all of the defined routes in your application. You can also go to http://localhost:[port]/routes while working in the rails server.

rails routes

Routes are defined in the config/routes.rb file.

#config/routes.rb

root 'pages#home'                    #Define a root path ('/')
get 'signin' => 'sessions#signin'    #Create route that maps a URL to controller action  
resources :users                     #Creates all routes for RESTful resource
resources :users, :only => [:index]  #Creates routes for certain actions
resources :users, :except=> [:index] #Creates routes except specified ones
get 'users/index'                    #Shorthand for connecting route to controller/action

Below is a table of all of the verb/path/action mappings. It uses a User model as an example.

HTTP Verb Path Controller#Action Usage
GET /users users#index display list of all users
GET /users/new users#new return HTML form for creating a new user
POST /users users#create create a new user
GET /users/:id users#show display specific user
GET /users/:id/:edit users#edit return an HTML form for editing a user
PATCH/PUT /users/:id users#update update a specific user
DELETE /users/:id users#destroy delete a specific user

Controller

New controllers are created in the app/controllers folder in your project. The controller is a Ruby class which inherits from ApplicationController and is declared like so:

#controllers/users_controller.rb

class UsersController < ApplicationController
#controller code goes here
end

You can use a private method to encapsulate permissible parameters for your controller.

#controllers/users_controller.rb

class UsersController < ApplicationController
#controller code goes here

private

   def user_params
      params.require(:user).permit(:username, :password, :email)
   end
end

You can also save some time by using the built in generator command for Controllers. This will create a new Controller, as well as associated views, tests, and assets.

rails g controller Users             #generates a Users Controller
rails g controller Users index show  #generates a Users Controller with specified actions, routes, and views

Model

New models are created in the app/models folder in your project. The model is a Ruby class which inherits from ApplicationRecord and is declared like so:

#models/user.rb

class User < ApplicationRecord
#model code goes here
end

You can save some time by using the built in model generator, which will create the model for you as well as a migration with table columns.

rails g model User                  #generates a user model
rails g model User username:string  #generates user model and migration with username column

Migrations

Migrations allow you to create, update, and delete database items and work together with rake tasks to run and make changes to the database.

rails db:create    #creates the database
rails db:migrate   #runs pending migrations in order
rails db:rollback  #rolls back the last migration
rails db:seed      #runs the seed file to populate db with seed data
rails db:drop      #drops the database

Migration data types are as follows:

  • :boolean
  • :date
  • :datetime
  • :decimal
  • :float
  • :integer
  • :primary_key
  • :references
  • :string
  • :text
  • :time
  • :timestamp

Migrations also have handy built in generators that allow you to quickly generate a migration for a specific resource.

rails g model User username:string email:string

This will generate a migration that looks like this.

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :username
      t.string :email

      t.timestamps null: false
    end
  end
end

If the name of the migration follows a format of AddXToY or RemoveXFromY where X is the column and Y is an existing table, a migration will be generated the adds or removes columns from the specified table.

rails g migration AddPasswordToUsers password:string  #adding column
rails g migration RemoveEmailFromUsers email:string   #removing column

The above will generate the following migrations:

#adding column
class AddPasswordToUsers < ActiveRecord::Migration
   def change
      add_column :users, :password, :string
      add_index :users, :password
   end
end

#removing column
class RemoveEmailFromUsers < ActiveRecord::Migration
   def change
      remove_column :users, :email, :string
   end
end

I hope you find this refresher cheat sheet helpful. This is by no means an exhaustive list. The intention of creating a guide like this is to provide a single place wherein a lot of commonly used Rails tidits can live together for quick reference. Feel free to leave any feedback you might have!

References used in compiling this list:
-Rails Command Line
-Rails Routing
-Action Controller Overview
-Active Model Basics
-Rails Migrations
-Ruby On Rails Cheatsheet

Top comments (0)