LoginSignup
3
3

More than 3 years have passed since last update.

Ruby on Rails APIモードのCRUD実装 【初学者のReact✗Railsアプリ開発 第5回】

Posted at

やったこと

  • Ruby on RailsのAPIモードでCRUDを実装する(ただし、更新(U)はなし)

前回の記事

Reactのreduxを用いたログイン処理周りの実装【初学者のReact✗Railsアプリ開発第4回】

参考にさせていただいた記事

実装手順

モデルとコントローラーの作成

$ docker-compose run api rails g model post content:string
$ docker-compose run api rails g controller api/v1/posts

生成されたマイグレーションファイルを編集します。

db/migrate/XXX_create_posts.rb
class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|
      t.string :content
      t.references :user, foreign_key: true

      t.timestamps
    end
    add_index :posts, [:user_id, :created_at]
  end
end
$ docker-compose run api rake db:migrate 

route.rb

route.rb
Rails.application.routes.draw do
 namespace :api, defaults: { format: :json } do
    namespace :v1 do
      ##省略##
      resources :posts
    end
 end
end

  • resourcesで、GET, POSTなど複数のルーティングを一気に設定できる。resourceとの違いに注意。

posts_controller

posts_controller
module Api
  module V1
    class PostsController < ApplicationController
      before_action :set_post, only: [:index, :show, :update, :destroy]
      before_action :authenticate_api_v1_user!

      def index
        posts = Post.all
        render json: { status: 'SUCCESS', message: 'Loaded posts', data: posts}
      end

      def show
        @user = @post.user
        json_data = {
          'post': @post,
          'user': {
            'name': @user.name,
            'nickname': @user.nickname,
            'image': @user.image
          }
        }
        render json: { status: 'SUCCESS', message: 'Loaded the post', data: json_data}
      end

      def create
        post = Post.new(post_params)
        if post.save
          render json: { status: 'SUCCESS', data: post}
        else
          render json: { status: 'ERROR', data: post.errors }
        end
      end

      def destroy
        @post.destroy
        render json: { status: 'SUCCESS', message: 'Delete the post', data: @post}
      end

      def update
      end

      private

      def set_post
        @post = Post.find(params[:id])
      end

      def post_params
        params.require(:post).permit(:content, :user_id)
      end

    end
  end
end  

models/post.rb

post.rb
class Post < ApplicationRecord
  belongs_to :user
end

Postmanを用いてAPIの動作確認をする

create

chromeのデベロッパーツール->Application->Local Storageからauth_tokenとかをコピーして、
スクリーンショット 2020-01-12 21.43.04.png
Postmanに貼り付ける。
スクリーンショット 2020-01-12 21.42.44.png
そしてlocalhost:3000/api/v1/postsにPOSTすると
スクリーンショット 2020-01-12 21.41.24.png
postが作成されたことが確認できます。

index

localhost:3000/api/v1/postsにGETすると
スクリーンショット 2020-01-12 21.45.34.png

show

localhost:3000/api/v1/posts/1にGETすると、idが1のpostが返されます。
スクリーンショット 2020-01-12 21.45.52.png

destroy

localhost:3000/api/v1/posts/1にDELETEすると、idが1のpostが消えます。
スクリーンショット 2020-01-12 21.46.06.png
indexで確認すると、消えています。
スクリーンショット 2020-01-12 21.46.17.png

3
3
0

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
3
3