Ruby on Rails Action Controller
🚀 Ruby on Rails Action Controller — The Complete Deep Dive Guide (From Request to Response!)
When a user clicks a button on your Rails app… 💡 What exactly happens behind the scenes?
How does the request travel from the browser → server → router → controller → model → view → and back?
Today, we’ll break down Ruby on Rails Action Controller in full depth — step by step, class by class, parameter by parameter.
🌍 1️⃣ The Journey Begins: HTTP Request
When a user hits:
https://yourapp.com/posts/1
The browser sends an HTTP request like:
GET /posts/1 HTTP/1.1
This request contains:
- 🛣 Path:
/posts/1 - 🔁 HTTP Verb:
GET - 📦 Headers
- 🧾 Cookies
- 🧮 Query Parameters
- 🔐 Session info
Now Rails takes over.
🔥 2️⃣ Rack — The Entry Point
Rails sits on top of Rack (Ruby Webserver Interface).
Flow:
Web Server (Puma)
↓
Rack Middleware Stack
↓
Rails Application
Rails app responds to:
call(env)
Where:
env= Huge Hash containing request details.
Example:
env["REQUEST_METHOD"] # => "GET"
env["PATH_INFO"] # => "/posts/1"
🛣 3️⃣ Routing Layer — config/routes.rb
The request now reaches:
# config/routes.rb
resources :posts
This automatically generates:
| HTTP Verb | Path | Controller | Action |
|---|---|---|---|
| GET | /posts | posts | index |
| GET | /posts/:id | posts | show |
| POST | /posts | posts | create |
| PATCH | /posts/:id | posts | update |
| DELETE | /posts/:id | posts | destroy |
So:
GET /posts/1
Matches:
PostsController#show
Routing internally creates:
{
controller: "posts",
action: "show",
id: "1"
}
This hash becomes params later.
🎯 4️⃣ Controller Instantiation
Now Rails loads:
class PostsController < ApplicationController
end
Important hierarchy:
ActionController::Base
↑
ApplicationController
↑
PostsController
What ActionController::Base Provides:
- Params handling
- Sessions
- Cookies
- Rendering
- Redirecting
- Filters (before_action)
- Strong Parameters
- CSRF Protection
⚙️ 5️⃣ Dispatch Process — Action Execution
Internally Rails runs something like:
PostsController.action(:show).call(env)
Which:
- Creates controller instance
- Sets request & response objects
- Runs callbacks
- Executes action method
🧠 6️⃣ The Action Method
Example:
def show
@post = Post.find(params[:id])
end
🔹 Where does params come from?
Rails builds params from:
- Route parameters (
:id) - Query parameters (
?page=2) - POST body parameters
Example:
/posts/1?page=2
params = {
"id" => "1",
"page" => "2",
"controller" => "posts",
"action" => "show"
}
params is an instance of:
ActionController::Parameters
🔐 7️⃣ Strong Parameters (Security Layer)
Rails protects mass assignment.
Example:
def post_params
params.require(:post).permit(:title, :content)
end
Why?
Because without this:
Post.create(params[:post])
Could allow malicious fields like:
admin: true
Strong parameters prevent that 🚫
🎛 8️⃣ Before, After & Around Actions
before_action :authenticate_user!
after_action :log_request
around_action :measure_time
Execution Flow:
before_action
↓
action method
↓
after_action
Around action wraps:
def measure_time
start = Time.now
yield
puts Time.now - start
end
🍪 9️⃣ Sessions & Cookies
Cookies:
cookies[:user_id] = 10
Sessions:
session[:user_id] = 10
Sessions are stored:
- Cookie Store (default)
- Redis
- Database
- Cache Store
🎨 🔟 Rendering Response
After action completes, Rails decides:
Case 1️⃣: Implicit Render
def show
@post = Post.find(params[:id])
end
Rails automatically renders:
app/views/posts/show.html.erb
Case 2️⃣: Explicit Render
render :edit
render json: @post
render plain: "Hello"
render status: 404
Case 3️⃣: Redirect
redirect_to posts_path
Sends:
HTTP 302 Redirect
🧩 1️⃣1️⃣ The Full Internal Processing Flow
Here’s the complete lifecycle:
1. Browser sends HTTP request
2. Web Server (Puma) receives
3. Rack middleware stack processes
4. Rails Router matches route
5. Controller class loaded
6. Controller instance created
7. Params constructed
8. before_actions run
9. Action method executes
10. Model interaction happens
11. View rendered
12. Response returned to browser
🏗 1️⃣2️⃣ Important Classes in Action Controller
📦 Core Classes
| Class | Responsibility |
|---|---|
| ActionController::Base | Main controller class |
| ActionController::API | Lightweight API-only controller |
| ActionDispatch::Request | Request object |
| ActionDispatch::Response | Response object |
| ActionController::Parameters | Params wrapper |
| ActionController::Metal | Minimal controller |
🧪 1️⃣3️⃣ Example Full Flow (POST Request)
POST /posts
Body:
{
"post": {
"title": "Rails",
"content": "Powerful framework"
}
}
Controller:
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render :new
end
end
Processing Steps:
- Route matches
create - Params extracted
- Strong params applied
- Model validation runs
- DB insert happens
- Redirect or render
🔥 1️⃣4️⃣ API Mode Controllers
If using:
class PostsController < ActionController::API
Rails:
- Skips view rendering
- Skips cookies by default
- Optimized for JSON APIs
Used in microservices & SPA backends.
🛡 1️⃣5️⃣ CSRF Protection
Rails automatically adds:
protect_from_forgery with: :exception
Prevents:
- Cross-Site Request Forgery attacks
Works using:
- Authenticity token
- Session verification
🚀 1️⃣6️⃣ Performance Tips
✅ Use before_action wisely
✅ Avoid heavy logic in controllers
✅ Use service objects
✅ Use eager loading
✅ Prefer head :ok when no body needed
🎯 1️⃣7️⃣ Best Practices
✔ Keep controllers thin ✔ Move business logic to models/services ✔ Use strong params always ✔ Use RESTful routes ✔ Avoid N+1 queries
💡 Final Mental Model
Think of Action Controller as:
🎛 The Traffic Police of Your Rails App
It:
- Receives request 🚦
- Verifies identity 🔐
- Extracts data 📦
- Calls business logic 🧠
- Sends response 📤
Without it, Rails app has no direction.
🏁 Final Words
If you master Action Controller, you understand:
- How requests flow
- How security works
- How rendering works
- How Rails truly processes web requests
And that’s where you become not just a Rails developer…
But a Rails Architect 💎🔥
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.