Ruby on Rails 4 Cheat Sheet
Made with by @ktornwall

Rails MVC Pattern

Models represent the objects in your application. These are tied to the tables in your database. Model names are singular — Postapp/models/post.rb
Controllers contain functions that are mapped to routes, and handle the endpoints for our application. Controller names are plural — PostsControllerapp/controllers/posts_controller.rb
Views define the HTML view for each endpoint in the application. View paths matches controller and function — app/views/posts/index.html.erb
Routes define the endpoints that our application serves. — config/routes.rb

App Structure

  • APP_NAME - root folder for your app
    • app - contains code for your app
      • controllers
        • posts_controller.rb
      • helpers - custom view helpers
      • models
        • post.rb
      • views
        • layouts
          • application.html.erb - root template for your app
        • posts
          • index.html.erb - names match controller actions
          • show.html.erb
    • bin - scripts to run gems
    • config - app configurations
      • environments - rails configs for each env
        • develop.rb
        • production.rb
        • test.rb
      • application.rb
      • database.yml - configures db connection
      • environmment.rb
      • routes.rb - defines routes for app
    • db
      • migrate - database migrations
      • schema.rb - database structure, look for basic model properties here
      • seeds.rb - default data to load in db
    • lib
    • log
    • public - static files served at root url
    • spec - RSpec unit tests

Common Patterns for Controllers

Queries
Get all records Post.all
Query for record by id Post.find(post_id)
Query for many records Post.where(state: :active)
Strong Parameters
params.require(:post).permit(:title)

Routes

In config/routes.rb, this generates the endpoints:
Rails.application.routes.draw do
  resources :posts
end
Method Route HTTP Used For
index /posts GET List
show /post/:id GET Show one
new /post/new GET Show form for new
create /posts POST Create new
edit /posts/:id/edit GET Show form for edit
update /posts/:id PUT Update model
destroy /posts/:id DELETE Deletes model

Command Line

Install dependencies bundle install
List Rails commands rails help
Start server rails server
Generate model rails generate model Post title:string
List Rake commands rake -T
List routes rake routes
Run migrations rake db:migrate