Action Controller는 Rails MVC의 오케스트레이터 역할을 하며, HTTP 요청을 처리하고 모델을 조회하여 뷰 또는 직렬화된 데이터를 렌더링합니다.
요청 매개변수 및 특수 해시
# 매개변수 (쿼리 문자열, 본문 페이로드 및 라우트 세그먼트)
params[:id]
params.require(:user).permit(:name, :email)
# 세션 스토리지
session[:user_id] = user.id
# 플래시 알림 메시지
flash[:notice] = "Welcome back!" # 다음 요청에서 표시
flash.now[:alert] = "Invalid password" # 현재 렌더링 시 표시
flash.keep # 다음 요청까지 플래시 값 유지
# 쿠키
cookies[:theme] = "dark"
cookies.signed[:user_id] = user.id
cookies.permanent[:remember] = token
콜백 (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
렌더링 및 리다이렉트
# 리다이렉트
redirect_to root_path, notice: "Saved successfully!"
redirect_to article_path(@article)
# 템플릿 및 JSON 렌더링
respond_to do |format|
format.html # Renders articles/show.html.erb
format.json { render json: @article }
format.xml { render xml: @article }
end
# 상태 코드
render :new, status: :unprocessable_entity
head :no_content