プロジェクト作成
-apiオプションで、apiモードと呼ばれるファイル群で構成してくれる(不要なものは削いでくれる)
rails new sample-api --api
モデル作成
データスキーマのこと
ここで定義したものがDBに反映することになる
rails g model Movie name:string category:string description:string year:integer
スキーマ作成
db/migrate/の中にできているスクリプトが実行される
rails db:migrate
初期データ登録
db/seeds.rb
movies = [
["cube", "cube", "in the cube", 2000],
["saw", "bathroom", "jigsaw", 2004],
]
movies.each do |movie|
Movie.create(name: name, category: category, description: description, year: year)
end
流し込む
rails db:seed
Railsコンソールでデータ流し込めているか確認
rails c --sandbox
3.1.2 :001 > Movie.all
TRANSACTION (0.0ms) begin transaction
Movie Load (0.1ms) SELECT "movies".* FROM "movies"
=>
[#<Movie:0x00007f185000dd30
id: 1,
name: "cube",
category: "cube",
description: "in the cube",
year: 2000,
created_at: Wed, 25 Jan 2023 03:47:26.029657000 UTC +00:00,
updated_at: Wed, 25 Jan 2023 03:47:26.029657000 UTC +00:00>,
#<Movie:0x00007f184bc32f48
id: 2,
name: "saw",
category: "bathroom",
description: "jigsaw",
year: 2004,
created_at: Wed, 25 Jan 2023 03:47:26.034091000 UTC +00:00,
updated_at: Wed, 25 Jan 2023 03:47:26.034091000 UTC +00:00>]
3.1.2 :002 >
ルーティング作成
uriパスを定義してあげる
config/routes.rb
Rails.application.routes.draw do
resources :movies, only: :index
end
コントローラ作成
rails g controller Movies
/moviesに来た時に返却するレスポンスを定義する
controllers/controller/movies_controller.rb
class MoviesController < ApplicationController
def index
movies = Movie.all
render status: 200, json: { movies: movies }
end
end
アクセスして確認
curl localhost:3000/movies
ちゃんと取れている
{"movies":[{"id":1,"name":"cube","category":"cube","description":"in the cube","year":2000,"created_at":"2023-01-25T03:47:26.029Z","updated_at":"2023-01-25T03:47:26.029Z"},{"id":2,"name":"saw","category":"bathroom","description":"jigsaw","year":2004,"created_at":"2023-01-25T03:47:26.034Z","updated_at":"2023-01-25T03:47:26.034Z"}]}⏎