OR REACH ME ON

    Understanding MVC with Ruby on Rails (With a Simple Blog Example)

    When I started working with Ruby on Rails, the concept that shaped my entire understanding of web development was MVC – Model, View, Controller. It’s simple in theory, but once you see it in action, it clicks.

    In this post, I’ll walk you through MVC using a basic blog app as an example.

    What is MVC?

    Model → Handles the data and business logic.

    View → The user interface (what the user sees).

    Controller → The middleman, connecting Models and Views.

    Rails follows this pattern strictly, which is why it’s so powerful for beginners.

    Step 1: The Model

    In Rails, models represent tables in the database. For our blog, we’ll have a simple  post  model:

    				
    					ruby
    # app/models/post.rb
    class Post < ApplicationRecord
      validates :title, presence: true
      validates :body, presence: true
    end
    				
    			

    This model ensures that every post has a title and  body.

    Step 2: The Controller

    Controllers handle requests from the browser and decide what to do.

    				
    					# app/controllers/posts_controller.rb
    class PostsController < ApplicationController
      def index
        @posts = Post.all
      end
      def show
        @post = Post.find(params[:id])
      end
      def new
        @post = Post.new
      end
      def create
        @post = Post.new(post_params)
        if @post.save
          redirect_to @post
        else
          render :new
        end
      end
      private
      def post_params
        params.require(:post).permit(:title, :body)
      end
    end
    				
    			

    Here, the controller:

    • Fetches all posts (index)

    • Shows one post (show)

    • Creates a new post (create)

    Step 3: The View

    Views are just HTML + Ruby (ERB).

    				
    					<!-- app/views/posts/index.html.erb -->
    <h1>All Posts</h1>
    <% @posts.each do |post| %>
      <h2><%= link_to post.title, post %></h2>
      <p><%= truncate(post.body, length: 100) %></p>
    <% end %>
    				
    			

    This loops through all posts and displays them.

    How It All Connects

    1. User visits /posts.

    2.Router sends the request to PostsController#index.

    3. The controller asks the Model for all posts.

    4. The View (index.html.erb)  displays them.

    That’s MVC in action.

    🎯 Final Thoughts

    Back when I first learned Rails, this clear separation of concerns gave me confidence to build real apps. Even today, the same MVC structure powers complex systems — just with more layers added on top.

    If you’re starting out, build a simple blog or todo app with MVC. It’s the best way to understand how Rails (and web development in general) really works.