Here are steps how to set up a Ruby on Rails backend with a React frontend to display associated data:
Start by creating a new Rails application or use an existing one.
rails new my-rails-app
cd my-rails-app
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
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
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
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 (); } export default PostList;Posts
{posts.map(post => (
- {post.title}
))}
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 && (); } export default PostDetail;)}{post.title}
{post.body}
Comments
{post.comments.map(comment => (
- {comment.body}
))}
Remember to add appropriate routes in your React application to handle different views and components.
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
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();