Action Controller acts as the orchestrator in Rails MVC, handling incoming HTTP requests, querying models, and rendering views or serialized data.
Request Parameters & Special Hashes
# Parameters (query string, body payload, and route segments)
params[:id]
params.require(:user).permit(:name, :email)
# Session storage
session[:user_id] = user.id
# Flash notifications
flash[:notice] = "Welcome back!" # Displayed on next request
flash.now[:alert] = "Invalid password" # Displayed on current render
flash.keep # Preserve flash values for another request
# Cookies
cookies[:theme] = "dark"
cookies.signed[:user_id] = user.id
cookies.permanent[:remember] = token
Callbacks (before_action)
class ArticlesController < ApplicationController
before_action :authenticate_user!
before_action :set_article, only: [:show, :edit, :update]
skip_before_action :authenticate_user!, only: [:index, :show]
private
def set_article
@article = Article.find(params[:id])
end
end
Rendering & Redirects
# Redirects
redirect_to root_path, notice: "Saved successfully!"
redirect_to article_path(@article)
# Rendering templates & JSON
respond_to do |format|
format.html # Renders articles/show.html.erb
format.json { render json: @article }
format.xml { render xml: @article }
end
# Status codes
render :new, status: :unprocessable_entity
head :no_content