Ruby on Rails: Common Syntax Explained
1. Model Declaration
class Post < ApplicationRecord
end
This connects to the 'posts' table in the database.
2. Migrations
class CreatePosts < ActiveRecord::Migration[7.0]
def change
create_table :posts do |t|
t.string :title
t.text :content
t.timestamps
end
end
end
3. Routes
Rails.application.routes.draw do
resources :posts
root "posts#index"
end
Generates RESTful routes for CRUD operations.
4. Controller Actions
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
Ruby on Rails: Common Syntax Explained
if @post.save
redirect_to @post
else
render :new
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
5. View Syntax (ERB)
<h1><%= @post.title %></h1>
<p><%= @post.content %></p>
<% %> runs silently; <%= %> outputs to HTML.
6. Form Helpers
<%= form_with model: @post, local: true do |form| %>
<%= form.label :title %>
<%= form.text_field :title %>
<%= form.label :content %>
<%= form.text_area :content %>
<%= form.submit %>
<% end %>
7. Model Validations
class Post < ApplicationRecord
validates :title, presence: true, length: { minimum: 5 }
validates :content, presence: true
end
8. Associations
class Post < ApplicationRecord
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :post
Ruby on Rails: Common Syntax Explained
end
9. ActiveRecord Queries
Post.all
Post.find(1)
Post.where(title: 'Hello')
Post.order(:created_at)
Post.first
10. Flash Messages
redirect_to post_path(@post), notice: "Post created successfully!"
In view:
<% if notice %>
<p><%= notice %></p>
<% end %>
11. Partials
<%= render "form", post: @post %>
File: _form.html.erb
12. Helpers
module PostsHelper
def format_date(date)
date.strftime("%B %d, %Y")
end
end
Used in view:
<p><%= format_date(@post.created_at) %></p>
13. Callbacks in Models
class Post < ApplicationRecord
before_save :capitalize_title
private
def capitalize_title
Ruby on Rails: Common Syntax Explained
self.title = title.capitalize
end
end
14. Layouts and Yield
<!DOCTYPE html>
<html>
<head>
<title>Blog</title>
</head>
<body>
<%= yield %>
</body>
</html>
15. Link Helpers
<%= link_to "Home", root_path %>
<%= link_to "Edit", edit_post_path(@post) %>
<%= link_to "Delete", post_path(@post), method: :delete, data: { confirm: "Are you
sure?" } %>