0% found this document useful (0 votes)
13 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)
13 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

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 [Link]

$ 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/[Link]

[Link]:
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:
[Link] # 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 < [Link]
[Link](: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

[Link](name: "Alice", email: "a@[Link]")


user = [Link](1)
[Link](title: "My Post", body: "Post body")
[Link](published: true).limit(5).order(created_at: :desc)

7. Common querying methods

[Link](id)
Model.find_by(email: "x")
[Link](active: true)
[Link](created_at: :desc)
[Link](10).offset(20)
[Link](:status).count
[Link](:comments)
[Link](:user)
[Link]("id, name").where("age > ?", 18)
[Link]?(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 = [Link]
end

def show
@article = [Link](params[:id])
end

def create
@article = [Link](article_params)
if @[Link]
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
[Link](:user).permit(:name, :email)
end

12. Views and erb

<%= @[Link] %>


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

13. Partials

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

_filename.[Link] is a partial

14. Forms and form helpers

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


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

<%= [Link] %>


<% end %>

f.text_area, f.check_box, [Link], f.collection_select

15. Rails server

$ rails server
$ rails s -p 3001 -b [Link]

You might also like