يعمل Action Controller كمنسق رئيسي في بنية MVC في ريلز، حيث يتعامل مع طلبات HTTP الواردة، ويستعلم من النماذج، ويصيّر العروض أو يرجع بيانات مسلسلة.
معاملات الطلب والمصفوفات الخاصة (Params & Hashes)
# المعاملات (سلسلة الاستعلام، حمولة الطلب، وأجزاء المسار)
params[:id]
params.require(:user).permit(:name, :email)
# تخزين الجلسات (Sessions)
session[:user_id] = user.id
# إشعارات الفلاش (Flash Messages)
flash[:notice] = "Welcome back!" # تظهر في الطلب التالي
flash.now[:alert] = "Invalid password" # تظهر في التصيير الحالي مباشرة
flash.keep # الاحتفاظ بقيم الفلاش لطلب إضافي
# ملفات تعريف الارتباط (Cookies)
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
التصيير وإعادة التوجيه (Rendering & Redirects)
# إعادة التوجيه
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