0% found this document useful (0 votes)
0 views5 pages

Rails Backend Cheatsheet

This document is a comprehensive cheat sheet for Ruby on Rails backend development, covering project setup, model generation, database commands, migrations, validations, querying methods, controller actions, routing, views, and forms. It provides command-line instructions, code examples, and explanations of key concepts and best practices. The cheat sheet is structured to serve as a quick reference for developers working with Ruby on Rails.

Uploaded by

martreza1092
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views5 pages

Rails Backend Cheatsheet

This document is a comprehensive cheat sheet for Ruby on Rails backend development, covering project setup, model generation, database commands, migrations, validations, querying methods, controller actions, routing, views, and forms. It provides command-line instructions, code examples, and explanations of key concepts and best practices. The cheat sheet is structured to serve as a quick reference for developers working with Ruby on Rails.

Uploaded by

martreza1092
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Ruby on Rails Comprehensive Backend Cheat Sheet

1. Project initiation and setup

$ rails new my_app -d postgresql --skip-javascript --skip-hotwire


$ cd my_app
$ bundle install
$ rails db:create
$ rails server

Environment structure:
- app/: core logic (MVC)
- config/: environment, routes, DB, initializers
- db/: seeds, schema, migrations
- test/ or spec/: unit/integration tests

2. Model generation, options and data types

$ rails g model Article title:string content:text published:boolean views:integer


published_at:datetime

Common data types:


:string, :text, :integer, :float, :decimal, :datetime, :date, :boolean, :binary, :uuid,
:jsonb

Options:
null: false
default: 0
index: true
foreign_key: true

Associations:
belongs_to, has_many, has_one, has_and_belongs_to_many

Self-reference:
class Employee < ApplicationRecord
belongs_to :manager, class_name: 'Employee', optional: true
has_many :subordinates, class_name: 'Employee', foreign_key: :manager_id

Join Tables (HABTM):


rails g migration CreateJoinTableArticlesCategories article category

To_table usage:
add_reference :orders, :buyer, foreign_key: { to_table: :users }

3. Database commands and schema.rb

$ rails db:create # Creates DBs


Ruby on Rails Comprehensive Backend Cheat Sheet

$ rails db:drop # Drops DBs


$ rails db:migrate # Migrates
$ rails db:reset # Drops + creates + migrates
$ rails db:seed # Loads db/seeds.rb

schema.rb:
Auto-generated canonical representation of DB (not SQL dump)
Used to recreate structure on new environments

4. Migrations and naming conventions

First-time:
rails g migration CreateProducts name:string price:decimal

Change column:
rails g migration AddViewsToArticles views:integer
rails g migration RemoveViewsFromArticles views:integer
rails g migration RenameViewsToHitsInArticles
rails g migration ChangeDataTypeForViews

Manual editing:
change_table, add_column, remove_column
add_index, add_foreign_key

Timestamps:
t.timestamps # Adds created_at, updated_at

5. Validations

class Post < ApplicationRecord


validates :title, presence: true
validates :slug, uniqueness: true
validates :views, numericality: { greater_than_or_equal_to: 0 }
validates :status, inclusion: { in: %w[draft published archived] }
validate :valid_future_publish_date

def valid_future_publish_date
if publish_at && publish_at < Time.current
errors.add(:publish_at, "must be in the future")
end
end
end

6. Rails console and sample data

$ rails console
Ruby on Rails Comprehensive Backend Cheat Sheet

User.create(name: "Alice", email: "[email protected]")


user = User.find(1)
user.posts.create(title: "My Post", body: "Post body")
Post.where(published: true).limit(5).order(created_at: :desc)

7. Common querying methods

Model.find(id)
Model.find_by(email: "x")
Model.where(active: true)
Model.order(created_at: :desc)
Model.limit(10).offset(20)
Model.group(:status).count
Model.joins(:comments)
Model.includes(:user)
Model.select("id, name").where("age > ?", 18)
Model.exists?(conditions)

8. Controller generation

$ rails g controller Articles index show new edit create update destroy

Options:
--skip-routes Don't add routes automatically
--skip-template-engine Avoid view templates

9. Routing

Manual:
get '/posts', to: 'posts#index'

resources :posts

resources :users do
resources :posts
end

resources :articles, only: [:index, :show]


resources :comments, except: [:destroy]

10. Controller actions

def index
Ruby on Rails Comprehensive Backend Cheat Sheet

@articles = Article.all
end

def show
@article = Article.find(params[:id])
end

def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render :new, status: :unprocessable_entity
end
end

11. Params, filtering, security

params[:id]
params[:user][:name]

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

12. Views and erb

<%= @user.name %>


<%= link_to "Edit", edit_user_path(@user) %>
<% if @user.admin? %> Admin Panel <% end %>
<%= render 'shared/header' %>

13. Partials

<%= render 'users/user', user: @user %>

_filename.html.erb is a partial

14. Forms and form helpers

<%= form_with model: @user do |f| %>


<%= f.label :name %>
<%= f.text_field :name %>
Ruby on Rails Comprehensive Backend Cheat Sheet

<%= f.submit %>


<% end %>

f.text_area, f.check_box, f.select, f.collection_select

15. Rails server

$ rails server
$ rails s -p 3001 -b 0.0.0.0

You might also like