Action Controller zarządza przepływem w Rails MVC: obsługuje żądania HTTP, komunikuje się z modelami i renderuje widoki.
Parametry żądania i specjalne hashe
# Parametry (query string, payload oraz segmenty ścieżki)
params[:id]
params.require(:user).permit(:name, :email)
# Przechowywanie sesji
session[:user_id] = user.id
# Komunikaty flash
flash[:notice] = "Welcome back!" # Wyświetlane przy następnym żądaniu
flash.now[:alert] = "Invalid password" # Wyświetlane przy bieżącym renderowaniu
flash.keep # Zachowanie wartości flash na kolejne żądanie
# Ciasteczka (Cookies)
cookies[:theme] = "dark"
cookies.signed[:user_id] = user.id
cookies.permanent[:remember] = token
Wywołania zwrotne (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
Renderowanie i przekierowania
# Przekierowania
redirect_to root_path, notice: "Saved successfully!"
redirect_to article_path(@article)
# Renderowanie szablonów i formatu JSON
respond_to do |format|
format.html # Renders articles/show.html.erb
format.json { render json: @article }
format.xml { render xml: @article }
end
# Kody statusu
render :new, status: :unprocessable_entity
head :no_content