LoginSignup
2
0

More than 1 year has passed since last update.

seedとfakerでランダムなユーザーデータを作成し、RailsでUser-APIを実装する。

Posted at

手順

1. APIモードで作成

2. モデル・コントローラの作成

3. ルーティングの設定

4. コントローラの設定

5. seedとFakerでランダムなサンプルデータを作成

6. test.httpファイルを作成して、HTTP要求の種類別に要求をしてみる

APIモードで作成

console
$ rails new user-api --api

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

今回はtitleというstringを持ったpostというテーブルを作成します。

$ rails g model post first_name:string last_name:string gender:integer

$ rails g controller users

$ rails db:create

$ rake db:migrate

ルーティングの設定

config/routes.rb

 Rails.application.routes.draw do
   resources :users
 end


コントローラの設定

コントローラの中身を外部からajaxリクエスト等で情報の作成・取得・削除・編集が可能になるよう設定します。

users.controller.rb

class UsersController < ApplicationController
  before_action :set_user, only: %i[show update destroy]

  def index
    users = User.order(created_at: :desc)
    render json: { status: 'SUCCESS', message: 'Loaded users', data: users }
  end

  def show
    render json: { status: 'SUCCESS', message: 'Loaded the user', data: @user }
  end

  def create
    user = User.new(user_params)
    if user.save
      render json: { status: 'SUCCESS', data: user }
    else
      render json: { status: 'ERROR', data: user.errors }
    end
  end

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

  def update
    if @user.update(user_params)
      render json: { status: 'SUCCESS', message: 'Updated the user', data: @user }
    else
      render json: { status: 'SUCCESS', message: 'Not updated', data: @user.errors }
    end
  end

  private

  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:first_name, :last_name, :gender)
  end
end

seedとFakerでランダムなサンプルデータを作成

1. fakerをインストールする

Gemfile

gem 'faker'
gem 'gimei'

gimeiは、日本人の名前や、日本の住所をランダムに返すGemです。

  • ひらがなの場合、Gimei.hiragana
  • カタカナの場合、Gimei.katakana
  • 漢字の場合、Gimei.kanji
bundle install

usersデーブルに50件のダミーデータを追加する。

seeds.rb

require 'faker'

50.times do |n|
  first_name = Gimei.first.kanji
  last_name = Gimei.last.kanji
  User.create!(
    first_name: first_name,
    last_name:  last_name,
    gender: rand(1..2)
  )
end
rails db:seed

APIを実行する

$ rails s

test.httpファイルを作成して、HTTP要求の種類別に要求をしてみる

GET(http://localhost:3000/users/:id) or (http://localhost:3000/users)

スクリーンショット 2021-11-22 15 11 48

POST(http://localhost:3000/users)

スクリーンショット 2021-11-22 15 14 19

PUT(http://localhost:3000/users/:id)

スクリーンショット 2021-11-22 15 13 50

DELETE(http://localhost:3000/users/:id)

スクリーンショット 2021-11-22 15 14 51

2
0
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
2
0