Here are steps how to set up a Ruby on Rails backend with a React frontend to display associated data:

1. Set Up a Ruby on Rails Backend

Start by creating a new Rails application or use an existing one.

rails new my-rails-app
cd my-rails-app

2. Create Models and Associations

a. Define your models and their associations in Rails. For example, if you have a blog application, you might have models like User and Post. Use Rails migrations to create the necessary database tables and associations.

# app/models/user.rb
class User < ApplicationRecord
  has_many :posts
end

# app/models/post.rb
class Post < ApplicationRecord
  belongs_to :user
  has_many :comments
end

b. Run migrations to create the database tables:
rails db:migrate

3. Set Up API Endpoints

a. Create API endpoints in your Rails application to expose the data. You can use Rails controllers and routes for this purpose. For example, you can create a controller for posts and define actions like index and show to fetch post data.

# app/controllers/api/posts_controller.rb
class Api::PostsController < ApplicationController
  def index
    @posts = Post.all
    render json: @posts
  end

  def show
    @post = Post.find(params[:id])
    render json: @post
  end
end

b. Configure routes:

# config/routes.rb
namespace :api do
  resources :posts, only: [:index, :show]
end

4. Set Up React Frontend

Create a React application within your Rails project or as a separate project. You can use a tool like Create React App to set up a new React project:

npx create-react-app my-react-app

5. Fetch Data from the Rails API

In your React application, use Axios or the `fetch` API to make HTTP requests to the Rails API endpoints you've created. You can fetch data in React components and display it as needed.

// src/components/PostList.js (Note: create folder components inside src and then create file PostList.js)

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function PostList() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    axios.get('/api/posts')
      .then(response => {
        setPosts(response.data);
      })
      .catch(error => {
        console.error(error);
      });
  }, []);

  return (
    

Posts

    {posts.map(post => (
  • {post.title}
  • ))}
); } export default PostList;

6. Display Associated Data

To display associated data, you can navigate to individual post pages and fetch associated data when needed. Here's a basic example:

// src/components/PostDetail.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function PostDetail({ match }) {
  const [post, setPost] = useState(null);

  useEffect(() => {
    axios.get(`/api/posts/${match.params.id}`)
      .then(response => {
        setPost(response.data);
      })
      .catch(error => {
        console.error(error);
      });
  }, [match.params.id]);

  return (
    
{post && (

{post.title}

{post.body}

Comments

    {post.comments.map(comment => (
  • {comment.body}
  • ))}
)}
); } export default PostDetail;

Remember to add appropriate routes in your React application to handle different views and components.

7. Start the Development Servers

Start both the Rails server and the React development server to see your application in action.

In the Rails project directory:

rails server(It will start on port 3000)

In the React project directory:
npm start(It will start on port 3001)

Note: React Modules can be installed by using npm install module_name

Make sure to configure CORS settings in your Rails application to allow requests from your React frontend

CORS setting:

ROR

1. Install rack cors gem
gem 'rack-cors'

2. Create config/initializes/cors.rb and update below code

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3001/'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

REACT
Write below code in JS file

const express = require('express');
const cors = require('cors');
const app = express();

Support On Demand!

Ruby on Rails