LoginSignup
5

More than 1 year has passed since last update.

Rails+Reactで何か作る(パート1:Rails準備編)

Posted at

はじめに

rails と react で何か作ろうと思います。
やったことをメモ&共有します。

railsとreactは別プロジェクトとして作成します。

最終的に
rails app は herokuへデプロイ
react app は firebase hostingへデプロイ
の予定です。

今回は、RailsAppを作成してテスト用のAPIを作成するところまでを行います。

環境

ツール バージョン
ruby 3.0.2p107
sqlite3 3.36.0
node v17.3.0
yarn 1.22.17
rails 7.0.0
git 2.26.2

Railsの準備

Railsをnewする

APIモードでrails アプリを作成する

$ rails new quiz_rails --api

とりあえず、git で first commit しておく

$ cd quiz_rails
$ git status
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    .gitattributes
    .gitignore
    .ruby-version
    Gemfile
    Gemfile.lock
    README.md
    Rakefile
    app/
    bin/
    config.ru
    config/
    db/
    lib/
    log/
    public/
    storage/
    test/
    tmp/
    vendor/

$ git add .
$ git commit -m "rails new quiz_rails --api"

とりえあず、起動してみる

$ rails server
=> Booting Puma
=> Rails 7.0.1 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.5.2 (ruby 3.0.2-p107) ("Zawgyi")
*  Min threads: 5
*  Max threads: 5
*  Environment: development
*          PID: 9149
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop

http://localhost:3000 をブラウザで表示

image.png

テストAPIを作成

モデルを作成

$ rails g model Chat content:string
      invoke  active_record
      create    db/migrate/20220115021134_create_chats.rb
      create    app/models/chat.rb
      invoke    test_unit
      create      test/models/chat_test.rb
      create      test/fixtures/chats.yml
db/migrate/20220115021134_create_chats.rb
class CreateChats < ActiveRecord::Migration[7.0]
  def change
    create_table :chats do |t|
      t.string :content

      t.timestamps
    end
  end
end

マイグレートしておく

$ rails db:migrate
== 20220115021134 CreateChats: migrating ======================================
-- create_table(:chats)
   -> 0.0028s
== 20220115021134 CreateChats: migrated (0.0029s) =============================

テスト用のデータを作る

db/seeds.rb
Chat.create(content: "Hello, world!")
Chat.create(content: "これはSeedで作ったメッセージです")
$ rails db:seed

コントローラーを作る

$ rails g controller api/v1/chats
      create  app/controllers/api/v1/chats_controller.rb
      invoke  test_unit
      create    test/controllers/api/v1/chats_controller_test.rb
app/controllers/api/v1/chats_controller.rb
class Api::V1::ChatsController < ApplicationController
  before_action :set_chat, only: %i[show destroy update]

  def index
    chats = Chat.all.order(:id)
    render json: chats
  end

  def show
    render json: @chat
  end

  def create
    chat = Chat.new(chats_params)
    if chat.save
      render json: chat
    else
      render json: chat.errors
    end
  end

  def update
    if @chat.update(chats_params)
      render json: @chat
    else
      render json: @chat.errors
    end
  end

  def destroy
    if @chat.destroy
      render json: @chat
    else
      render json: @chat.errors
    end
  end

  private

  def set_chat
    @chat = Chat.find(params[:id])
  end

  def chats_params
    params.require(:chat).permit(:content)
  end
end

curl コマンドで確認

$ curl http://localhost:3000/api/v1/chats
[{"id":1,"content":"Hello, world!","created_at":"2022-01-15T02:27:46.274Z","updated_at":"2022-01-15T02:27:46.274Z"},{"id":2,"content":"これはSeedで作ったメッセージです","created_at":"2022-01-15T02:27:46.279Z","updated_at":"2022-01-15T02:27:46.279Z"}]

git にコミット

$ git status
On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
    modified:   config/routes.rb
    modified:   db/seeds.rb

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    app/controllers/api/
    app/models/chat.rb
    db/migrate/
    db/schema.rb
    test/controllers/api/
    test/fixtures/chats.yml
    test/models/chat_test.rb

no changes added to commit (use "git add" and/or "git commit -a")

$ git add .
$ git commit -m "add test api"

おわりに。

久々にrails触りましたが、基本的なことは昔(3年前)くらいと変わってなさそうですね
ControllerとModelを別々に rails g しましたが、
そういえば、一発で作るとか出来たような、そっちでやればよかったかなとも思っています。
今度やってみます。

おわり。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5