Hur man konfigurerar ett Ruby on Rails v7-projekt med ett React-frontend på Ubuntu 20.04

Introduktion

Ruby on Rails (RoR) är en kraftfull verktygslåda för webbapplikationer som underlättar skapandet av robusta och skalbara webblösningar. React, å andra sidan, är ett välkänt JavaScript-bibliotek för att utveckla interaktiva användargränssnitt (UI). Genom att para ihop RoR och React kan utvecklare skapa avancerade webbapplikationer med en smidig backend och en snabb frontend.

Denna handledning leder dig steg för steg genom konfigurationen av ett RoR v7-projekt med en React-frontend på Ubuntu 20.04. Detta arbetssätt kombinerar fördelarna med RoRs robusta backend och Reacts responsiva frontend.

Förutsättningar

Innan du börjar behöver du följande:

  • En server med Ubuntu 20.04 installerat
  • Ruby version 3.0 eller senare
  • Node.js version 16 eller senare
  • Yarn pakethanterare

Steg-för-steg-anvisningar

Steg 1: Skapa ett Ruby on Rails-projekt

1. Initiera ett nytt RoR-projekt med kommandot nedan:

rails new ror-react

2. Navigera till projektkatalogen:

cd ror-react

Steg 2: Installera React Frontend

1. Skapa en ny React-app i projektkatalogen:

npx create-react-app client --template @snowpack/app-template-react

2. Flytta Reacts klientkatalog till ”client/” i RoR-projektets mappstruktur:

mv client/* client/

3. Installera React-beroenden:

cd client && yarn install

Steg 3: Konfigurera API-vägar

1. Generera en ny API-kontroller i RoR:

rails generate controller api/v1/todos

2. Definiera API-funktioner i app/controllers/api/v1/todos_controller.rb:

class Api::V1::TodosController < ApplicationController
  def index
    @todos = Todo.all
    render json: @todos
  end

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

  def create
    @todo = Todo.create(todo_params)
    render json: @todo
  end

  def update
    @todo = Todo.find(params[:id])
    if @todo.update(todo_params)
      render json: @todo
    else
      render json: @todo.errors, status: :unprocessable_entity
    end
  end

  def destroy
    @todo = Todo.find(params[:id])
    @todo.destroy
    head :no_content
  end

private

  def todo_params
    params.require(:todo).permit(:title, :description)
  end
end

Steg 4: Konfigurera React-applikationen

1. I client/package.json, lägg till följande skript:

{
  "scripts": {
    "start": "snowpack dev",
    "build": "snowpack build"
  }
}

2. Skapa en ny komponent i client/src/components/Todo.js:

import React, { useState, useEffect } from "react";
import { getAllTodos, createTodo, deleteTodo, updateTodo } from "./api";

const Todo = ({ todo, updateTodos }) => {
  const [editing, setEditing] = useState(false);
  const [title, setTitle] = useState(todo.title);
  const [description, setDescription] = useState(todo.description);

  useEffect(() => {
    setTitle(todo.title);
    setDescription(todo.description);
  }, [todo]);

  const handleEdit = () => {
    setEditing(!editing);
  };

  const handleUpdate = async () => {
    const updatedTodo = await updateTodo(todo.id, { title, description });
    updateTodos(updatedTodo);
    setEditing(false);
  };

  const handleDelete = async () => {
    await deleteTodo(todo.id);
    updateTodos();
  };

  return (
    <div>
      {editing ? (
        <>
          <input value={title} onChange={(e) => setTitle(e.target.value)} />
          <input value={description} onChange={(e) => setDescription(e.target.value)} />
          <button onClick={handleUpdate}>Uppdatera</button>
          <button onClick={handleEdit}>Avbryt</button>
        </>
      ) : (
        <>
          <p>{title}</p>
          <p>{description}</p>
          <button onClick={handleEdit}>Redigera</button>
          <button onClick={handleDelete}>Ta bort</button>
        </>
      )}
    </div>
  );
};

export default Todo;

3. Skapa en ny komponent i client/src/components/Todos.js:

import React, { useState, useEffect } from "react";
import { getAllTodos, createTodo } from "./api";
import Todo from "./Todo";

const Todos = () => {
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    const fetchTodos = async () => {
      const todos = await getAllTodos();
      setTodos(todos);
    };
    fetchTodos();
  }, []);

  const handleCreateTodo = async (todo) => {
    const newTodo = await createTodo(todo);
    setTodos([...todos, newTodo]);
  };

    const updateTodos = (updatedTodo) => {
    setTodos(todos.map((todo) => (todo.id === updatedTodo.id ? updatedTodo : todo)));
  };


  return (
    <div>
      <h1>Todos</h1>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>
            <Todo todo={todo} updateTodos={updateTodos} />
          </li>
        ))}
      </ul>
      <button onClick={() => handleCreateTodo({ title: "", description: "" })}>Ny Todo</button>
    </div>
  );
};

export default Todos;

Steg 5: Konfigurera proxy och byggkommandon

1. I client/snowpack.config.mjs, lägg till följande proxy-konfiguration:

export default {
  mount: {
    public: "/",
    src: "/dist"
  },
  plugins: [
    ["snowpack-plugin-react-refresh"],
    ["snowpack-plugin-dotenv"],
    [
      "snowpack-plugin-proxy",
      {
        routes: [
          {
            match: "/api/v1/todos/*",
            src: "http://localhost:3000/api/v1/todos/*"
          }
        ]
      }
    ]
  ],
  devOptions: {
    open: "none"
  },
  buildOptions: {
    baseUrl: "/client/dist/"
  }
};

2. I client/package.json, lägg till följande byggkommando:

{
  "scripts": {
    "start": "snowpack dev",
    "build": "snowpack build",
    "build:prod": "snowpack build --env production"
  }
}

Starta applikationen

1. Starta RoR-servern:

rails s

2. Bygg React-klienten:

cd client && yarn build:prod

3. Kopiera den byggda React-klientmappen till RoRs ”public/”-katalog:

cp -r client/dist/ public/client

Applikationen är nu aktiv och tillgänglig på http://localhost:3000.

Sammanfattning

Genom att följa instruktionerna i denna guide har du skapat ett Ruby on Rails v7-projekt med en React-frontend på Ubuntu 20.04. Denna konfiguration ger dig en kraftfull och flexibel utvecklingsmiljö för att bygga komplexa webbapplikationer med skalbar backend och responsiv frontend. Denna kombination av tekniker ger ett robust och högpresterande ramverk för dina projekt.

Vanliga frågor (FAQ)

1. Vilken version av Ruby on Rails används i denna guide?
> Ruby on Rails v7

2. Vilken version av React används i denna guide?
> React v17 (medföljer create-react-app)

3. Vilken version av Node.js används i denna guide?

> Node.js version 16 eller senare