LoginSignup
0
0

More than 1 year has passed since last update.

Rails scaffoldコマンドの使い方

Last updated at Posted at 2021-07-31

scaffoldとは

scaffoldとは雛形を作成するコマンド。scaffoldは『はしご』という意味。
Railsではしごをかけて簡単に雛形を作成できるコマンドです。

scaffolfコマンド

$ rails g scaffold<model名> カラム名:型

指定したmodelと対応するためRESTfulなAPIを作成するためのコマンのド

#REST APIの雛形を作成 *ここではarticle modelとする
$ bundle exec rails g scaffold articles title:string body:text

*REST APIの説明はこちら
https://qiita.com/Hashimoto-Noriaki/items/d69c9dd0643f241776a9

generatoの設定

$ bundle exec rails d scaffold article title:string body:text

で作成したファイルを削除。その後generatorの設定。

config/applixation.rb
module HelloWorldRails
  class Application < Rails::Application

        #省略

    # the framework and any gems in your application.
    config.generators do |g|
      g.javascripts false
      g.stylesheets false
      g.helper false
      g.test_framework false
+     g.template_engine false  #追加
    end

+   config.api_only = true
  end
end

*template_engineはgeneratorによってhtml.erbファイルを作るかどうかの設定。
WebAPIではJSONを返すのが目的なのでjson.jbuilderだけを作るようにする。

*api_onlyはtrueにすることによってAPI実装で必要な部分だけが作成されるようになるオプション。

scaffolfコマンドの実行とファイル確認

$ bundle exec rails g scaffold articles title:string body:text

作られたファイルは以下の通り
1 migrationファイル
2 model
3 routes.rbに対応するルーティングの追加
4controller
5view(先ほど行った設定によりjbuilderファイルのみ)

controllerの確認

今回はarticle_controller.rb。scaffoldを作る理由はcontrollerの実装が綺麗で
お手本になるから。

articles_controller.rb

class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :update, :destroy]

  # GET /articles
  # GET /articles.json
  def index
    @articles = Article.all
  end

  # GET /articles/1
  # GET /articles/1.json
  def show
  end

  # POST /articles
  # POST /articles.json
  def create
    @article = Article.new(article_params)

    if @article.save
      render :show, status: :created, location: @article
    else
      render json: @article.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /articles/1
  # PATCH/PUT /articles/1.json
  def update
    if @article.update(article_params)
      render :show, status: :ok, location: @article
    else
      render json: @article.errors, status: :unprocessable_entity
    end
  end

  # DELETE /articles/1
  # DELETE /articles/1.json
  def destroy
    @article.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_article
      @article = Article.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def article_params
      params.require(:article).permit(:title, :body)
    end
end

*具体的にはメソッドの数が変わってます。
JSONを返すようなWebAPIでは new editメソッドは使わない。
現状はREST APIに必要な最低限の実装になっている。

追加されたメソッド の確認
1 index
2 show
3 create
4 update
5 destroy

*Readはindex(一覧表示)とshow(詳細ページ)に分かれる。
scaffoldコマンド一発でCRUD処理に対応することがわかる。

modelとmigrationファイル

・model/article.rb
・db/migration/****_create_articles.rb

articleモデルが追加されたのとarticlesテーブルを作る新しいmigrationファイルが作成されている。

⚫︎routes.rb
自動的に必要なルーティングが追加

routes.rb
Rails.application.routes.draw do
 +  resources :articles
    get "users/index"
    get "homes/index"

end

追加されたのは1行だが
routes.rb に resources の記述が追加されると CRUD 処理で必要なルーティングが追加される。

resources の記述一つだけで、6 つのルーティングが追加

view

view には3つのファイルが作成される。
① index.json.jbuilder

② show.json.jbuilder

③ _article.json.jbuilder

*_article.json.jbuilderとは部分テンプレート(partical)と呼ばれるもので、コードを共通化させるます。

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