All guides
Intermediate-AdvancedSelf-pacedFree GuideSection 8/33

Architecture MVC

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.2.3 : Architecture MVC

🎯 Objectif pédagogique

Comprendre le pattern MVC qui structure toute application Rails, et l'implémenter en Ruby pur avant de passer au framework.


MVC : séparer les responsabilités

  • →Model : données et logique métier
  • →View : présentation et affichage
  • →Controller : orchestration entre Model et View
Loading diagram…

MVC en Ruby pur

# Model
class Recette
  attr_accessor :nom, :description
  attr_reader :id

  @@toutes = []
  @@prochain_id = 1

  def initialize(attrs = {})
    @id = @@prochain_id
    @@prochain_id += 1
    @nom = attrs[:nom]
    @description = attrs[:description]
    @@toutes << self
  end

  def self.all
    @@toutes
  end

  def self.find(id)
    @@toutes.find { |r| r.id == id }
  end

  def to_s
    "#{@nom} - #{@description}"
  end
end

# View
class RecetteView
  def afficher_liste(recettes)
    puts "\n--- Mes Recettes ---"
    recettes.each_with_index do |r, i|
      puts "#{i + 1}. #{r}"
    end
  end

  def demander_nom
    print 'Nom : '
    gets.chomp
  end
end

# Controller
class RecetteController
  def initialize
    @view = RecetteView.new
  end

  def liste
    @view.afficher_liste(Recette.all)
  end

  def creer
    nom = @view.demander_nom
    Recette.new(nom: nom)
  end
end

# Router
class Router
  def initialize(controller)
    @controller = controller
  end

  def run
    loop do
      puts "\n1. Lister  2. Ajouter  3. Quitter"
      choix = gets.chomp.to_i
      case choix
      when 1 then @controller.liste
      when 2 then @controller.creer
      when 3 then break
      end
    end
  end
end

Responsabilités MVC

CoucheResponsabilitéFichiers RailsExemple
ModelDonnées et logique métierapp/models/User.rb
ViewTemplates et affichageapp/views/index.html.erb
ControllerOrchestration requête/réponseapp/controllers/UsersController.rb
RouterURL vers actionsconfig/routes.rbget /users

← Scroll horizontally →

Quick Check

Dans MVC, où se trouve la validation d'un email ?

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.