やったこと
- 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とかをコピーして、
Postmanに貼り付ける。
そしてlocalhost:3000/api/v1/postsにPOSTすると
postが作成されたことが確認できます。
index
localhost:3000/api/v1/postsにGETすると
show
localhost:3000/api/v1/posts/1にGETすると、idが1のpostが返されます。
destroy
localhost:3000/api/v1/posts/1にDELETEすると、idが1のpostが消えます。
indexで確認すると、消えています。