AI Generated Cheatsheets

Ruby on Rails Cheatsheet

Overview

Installation

Creating a New Rails Application

Routing

Controllers

Models

Views

Migrations

Example

# Example Rails controller
class UsersController < ApplicationController
  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to @user
    else
      render 'new'
    end
  end

  private

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

This Rails controller defines four actions: index, show, new, and create. The index action retrieves all users from the database and assigns them to the @users instance variable. The show action retrieves a single user based on the id parameter. The new action creates a new User object. The create action creates a new User object based on the parameters submitted in a form and saves it to the database. If the user is saved successfully, the user is redirected to their show page. If there are validation errors, the user is shown the new user form again with error messages.

Resources