Skip to content

Ror Mvc

DodaTech 3 min read

title: Ruby on Rails MVC — Complete Guide to Model-View-Controller description: 'Learn Ruby on Rails MVC: models handle data, views render templates, controllers coordinate requests, RESTful resources, and clean separation of concerns.' date: 2026-06-28 lastmod: 2026-06-28 weight: 13 tags: [backend, ror]


Ruby on Rails MVC separates application code into Models (data), Views (presentation), and Controllers (request handling), following RESTful conventions for clean architecture.

## What You'll Learn

By the end of this tutorial, you'll understand the Rails MVC architecture, create models with Active Record, build views with ERB, implement controllers, and follow RESTful resource conventions.

## Real-World Use

A blog app has a Post model (database), PostsController (handles HTTP requests), and views for index/show (HTML). CRUD operations map to RESTful actions: index, show, new, create, edit, update, destroy.

## MVC Learning Path

```mermaid
flowchart LR
  A[Installation] --> B[MVC]
  B --> C[Routing]
  C --> D[Controllers]
  D --> E[Views]
  B --> F{You Are Here}
  style F fill:#f90,color:#fff

Model

# app/models/post.rb
class Post < ApplicationRecord
  validates :title, presence: true, length: { minimum: 5 }
  validates :body, presence: true
  belongs_to :user
  has_many :comments, dependent: :destroy
  scope :published, -> { where(published: true) }
  scope :recent, -> { order(created_at: :desc).limit(5) }
end

Controller

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  def index
    @posts = Post.published.recent
  end
  def show
  end
  def new
    @post = Post.new
  end
  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to @post, notice: "Post created successfully."
    else
      render :new, status: :unprocessable_entity
    end
  end
  private
  def set_post
    @post = Post.find(params[:id])
  end
  def post_params
    params.require(:post).permit(:title, :body, :published)
  end
end

View (ERB)

<!-- app/views/posts/index.html.erb -->
<h1>Blog Posts</h1>
<% @posts.each do |post| %>
  <article>
    <h2><%= link_to post.title, post %></h2>
    <p><%= truncate(post.body, length: 200) %></p>
    <small>Posted <%= time_ago_in_words(post.created_at) %> ago</small>
  </article>
<% end %>
<%= link_to "New Post", new_post_path %>

RESTful Resources

# config/routes.rb
Rails.application.routes.draw do
  resources :posts     # Creates 7 RESTful routes
  # GET    /posts          -> posts#index
  # GET    /posts/new      -> posts#new
  # POST   /posts          -> posts#create
  # GET    /posts/:id      -> posts#show
  # GET    /posts/:id/edit -> posts#edit
  # PATCH  /posts/:id      -> posts#update
  # DELETE /posts/:id      -> posts#destroy
end

Common Mistakes

1. Fat Models, Skinny Controllers

Business logic belongs in models, not controllers. A controller action should be 2-5 lines.

2. Logic in Views

Views should only display data. No complex Ruby logic, queries, or business rules in ERB.

3. Not Using Strong Parameters

params.require.permit whitelists attributes. Without strong params, mass assignment vulnerabilities exist.

4. Skipping Validation

Model validations prevent invalid data. Always validate presence, uniqueness, format, and associations.

5. Ignoring RESTful Conventions

Adding custom actions outside RESTful routes (posts/approve instead of custom controller) makes code harder to maintain.

Practice Questions

1. What are the three MVC components in Rails?

Model (data), View (template/HTML), Controller (request handling). Each has a specific responsibility.

2. What is a RESTful resource in Rails?

resources :posts generates 7 standard routes (index, show, new, create, edit, update, destroy) following REST conventions.

3. Why use strong parameters?

Strong parameters require explicit permission for mass assignment, preventing users from setting protected attributes.

4. What is the purpose of before_action?

before_action runs a method before specified controller actions to DRY up common logic (finding records, authentication).

5. Challenge: Create a complete MVC for a Comment model with validations and associations.

rails generate model Comment body:text post:references user:references
rails generate controller Comments
# Edit routes: resources :comments
# Add validates :body, presence: true
# Add belongs_to :post, :user

FAQ

What is the difference between render and redirect_to?

render renders a template (same request). redirect_to sends a new HTTP request. Use redirect after successful mutations.

Where do helper methods go?

View helpers go in app/helpers/ modules. Controller helpers can be private methods in the controller or ApplicationController.

What is the purpose of ApplicationRecord?

Base class for all models. Add shared logic (scopes, methods) here that applies to all models.

Can I use any template engine besides ERB?

Yes. Slim, Haml, and Builder are popular alternatives. Set the template engine in Gemfile.

What is the flash hash?

flash[:notice] and flash[:alert] display one-time messages to users after redirects.

Mini Project: Blog MVC

Create a complete blog with Post model, controller, views, and RESTful routes.

rails generate scaffold Post title:string body:text published:boolean
rails db:migrate
# Visit /posts

What's Next

Ruby on Rails Routing Ruby on Rails Controllers

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro