All guides
Intermediate-AdvancedSelf-pacedFree GuideSection 20/33

Rails MVC — routing et controllers

Learn to build and check a web application with development tools and AI assistants. Practise design, coding and validation.

The full lessons for this course are currently available in French. Use the section menu to navigate the French course.

💡

Free content, available without an account. Tools and models change: use the current model guide to check their versions. Models and sources

Section 13.5.1 : Rails MVC — routing et controllers

🎯 Objectif pédagogique

Comprendre l'architecture MVC de Rails, maîtriser le système de routing RESTful et créer des controllers efficaces qui orchestrent la logique de votre application.


Le pattern MVC dans Rails

MVC (Model-View-Controller) est le patron architectural central de Rails. Chaque requête HTTP suit un chemin clair :

Loading diagram…

Le Router : le GPS de Rails

Le router traduit les URLs en actions de controllers. Rails suit la convention REST :

# config/routes.rb

Rails.application.routes.draw do
  # Ressource RESTful complète (7 routes)
  resources :articles

  # Cela génère automatiquement :
  # GET    /articles          => articles#index
  # GET    /articles/new      => articles#new
  # POST   /articles          => articles#create
  # GET    /articles/:id      => articles#show
  # GET    /articles/:id/edit => articles#edit
  # PATCH  /articles/:id      => articles#update
  # DELETE /articles/:id      => articles#destroy

  # Ressources imbriquées
  resources :articles do
    resources :comments, only: [:create, :destroy]
  end
  # => POST /articles/:article_id/comments

  # Route personnalisée
  get '/about', to: 'pages#about'

  # Root route
  root 'pages#home'
end

Les Controllers

Un controller est une classe Ruby qui reçoit les requêtes et coordonne la réponse :

# app/controllers/articles_controller.rb

class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit, :update, :destroy]

  def index
    @articles = Article.all.order(created_at: :desc)
  end

  def show
    # @article est défini par before_action
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article, notice: 'Article créé avec succès.'
    else
      render :new, status: :unprocessable_entity
    end
  end

  def edit
    # @article est défini par before_action
  end

  def update
    if @article.update(article_params)
      redirect_to @article, notice: 'Article mis à jour.'
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @article.destroy
    redirect_to articles_path, notice: 'Article supprimé.'
  end

  private

  def set_article
    @article = Article.find(params[:id])
  end

  def article_params
    params.require(:article).permit(:title, :content, :published)
  end
end

Strong Parameters

Rails utilise les Strong Parameters pour se protéger contre l'injection de paramètres (mass assignment) :

# DANGEREUX : accepte tout
@article = Article.new(params[:article])

# SÉCURISÉ : filtre les paramètres autorisés
@article = Article.new(article_params)

private

def article_params
  params.require(:article).permit(:title, :content, :published)
  # Seuls title, content et published sont acceptés
  # Tout autre paramètre (is_admin, user_id...) est ignoré
end

Filtres (Callbacks)

class ApplicationController < ActionController::Base
  # Exécuté avant chaque action
  before_action :authenticate_user!

  # Exécuté après
  after_action :log_activity

  # Conditionnel
  before_action :set_article, only: [:show, :edit, :update, :destroy]
  before_action :check_admin, except: [:index, :show]
end
Quick Check

Quelle commande terminal crée les 7 routes RESTful pour une ressource 'products' dans Rails ?

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed

Your progress

Progress is self-reported and stored in your browser. The final completion record is not a qualification or an independent assessment.

View progress and completion record

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed

One practical AI workflow in your inbox

Methods, resources and new exercises. Free, unsubscribe at any time.