Building a Full Stack Application with Ruby on Rails and React within the MVC Architecture
Minchul An
Posted on October 20, 2023
In the ever-evolving landscape of web development, constructing user-friendly platforms is crucial. One key to achieving this lies in understanding and implementing architectural patterns like the Model-View-Controller (MVC) architecture. MVC divides an application into three interconnected components: the Model, the View, and the Controller.
Understanding the Model-View-Controller (MVC) Architecture:
Model: The Model represents the application's data and logic. In our case, it's the backend logic and the database in Ruby on Rails. In the example below, the Post
model encapsulates the data structure, defining attributes like title
and content
. It ensures data integrity, validating user inputs and managing interactions with the database.
View: The View focuses on presenting the data to users. In our setup, React components, such as the PostsList
, act as the View. They render the data fetched from the backend, providing the visual interface users interact with.
Controller: The Controller serves as an intermediary between the Model and the View. In our architecture, the Rails PostsController
takes center stage. It receives requests from the frontend, interacts with the Model to retrieve or store data, and then sends the processed data to the View for display. The Controller ensures seamless communication between the backend and the frontend.
Now, Let's Dive Deeper:
Set up the Backend with Ruby on Rails:
Ruby on Rails is renowned for its convention-over-configuration approach. Here's how we initiate our backend development:
Step 1: Generate a new Rails application:
$ rails new myapp
Step 2: Create a Post model:
$ rails g model Post title:string content:text
$ rails db:migrate
Step 3: Define the API endpoints in the controller:
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.all
render json: @posts
end
def create
@post = Post.new(post_params)
if @post.save
render json: @post, status: :created
else
render json: @post.errors, status: :unprocessable_entity
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
In the above code, we define the PostsController
with the index
and create
actions. The index
action retrieves all posts from the database and renders them as a JSON response. The create
action creates a new post based on the parameters received and returns the created post or error messages in JSON format.
Configuring the Frontend with React:
React, a popular JavaScript library for building user interfaces, integrates seamlessly with our Rails backend. Here's how you set it up:
Step 1: Set up a React application using Create React App
npm create-react-app myapp_frontend
Step 2: Create a PostsList
component to fetch and display posts:
import React, { useEffect, useState } from 'react';
function PostsList() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('/posts')
.then(response => response.json())
.then(data => setPosts(data));
}, []);
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
))}
</div>
);
}
export default PostsList;
In the PostsList
component, we use React's useEffect
hook to fetch the posts data from the Rails backend API endpoint (/posts
) when the component mounts. The fetched data is stored in the posts
state variable and then mapped to render each post's title and content.
Integrating Backend and Frontend in the MVC Architecture:
To unify our Rails backend and React frontend, we configure the frontend to communicate with the backend API endpoints via the routes.rb file. Linking React components to these endpoints enables seamless data exchange between the frontend and backend.
# config/routes.rb
Rails.application.routes.draw do
resources :posts, only: [:index, :create]
end
This sets up the necessary routes for the PostsController
actions.
Lastly, incorporate the PostsList
component into your React application to display the posts.
Conclusion:
By harnessing the capabilities of Ruby on Rails as the backend framework and React as the frontend library within the MVC architecture, we establish a solid foundation for a full stack web application. This overview only covers the essentials of this integration. Rails manages the backend intricacies, ensuring data accuracy and consistency, while React empowers us with a dynamic and interactive user interface. Although this overview provides just a glimpse, the potential of this integration in web development is vast and exciting.
Happy coding!
Posted on October 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 20, 2023