0
0
Ruby on Railsframework~5 mins

MVC architecture in Rails

Choose your learning style9 modes available
Introduction

MVC helps organize your web app by separating data, user interface, and control logic. This makes your code easier to manage and change.

Building a web app that needs to show data to users and let them change it
Creating a blog where posts are stored, shown, and edited
Making an online store with products, shopping carts, and orders
Developing a social media site where users interact with content
Working on any Rails app to keep code clean and organized
Syntax
Ruby on Rails
Model: app/models/*.rb
Controller: app/controllers/*_controller.rb
View: app/views/<controller_name>/*.html.erb

Model handles data and business rules.

Controller responds to user actions and talks to Model and View.

Examples
This is a Model representing posts in the database.
Ruby on Rails
class Post < ApplicationRecord
  # Model code here
end
This Controller fetches all posts to show in the view.
Ruby on Rails
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end
This View displays the list of post titles.
Ruby on Rails
<!-- app/views/posts/index.html.erb -->
<h1>All Posts</h1>
<ul>
  <% @posts.each do |post| %>
    <li><%= post.title %></li>
  <% end %>
</ul>
Sample Program

This example shows a simple MVC setup in Rails. The Article model represents data. The ArticlesController fetches all articles. The view lists article titles.

Ruby on Rails
class Article < ApplicationRecord
end

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end
end

<!-- app/views/articles/index.html.erb -->
<h1>Articles</h1>
<ul>
  <% @articles.each do |article| %>
    <li><%= article.title %></li>
  <% end %>
</ul>
OutputSuccess
Important Notes

Controllers should be thin; keep business logic in models.

Views should only display data, not change it.

Use Rails generators to create MVC files quickly.

Summary

MVC splits your app into Model, View, and Controller parts.

Model manages data, Controller handles requests, View shows output.

This separation keeps your code clean and easier to update.