LoginSignup
0
0

More than 5 years have passed since last update.

Scaffolding機能(編集中)

Last updated at Posted at 2019-04-09

Scaffolding機能によるアプリケーション開発

定型的なCRUD機能を持ったアプリの構築する為の機能(Scaffolding→足場という意味)
booksテーブルを操作する関連ファイルをまとめて作成

# ターミナルにおいて実行
# bookはモデル名
rails generate scaffold book isbn:string title:string price:integer publish:string published:date dl:boolean
#book以下は、booksテーブルのカラム名と、その型を示す(自分の実装に合わせて)

新規アプリケーションと、DBはまず自分で作成しておく必要がある
ただし、マイグレーションファイルだけは自分で実行する必要

自動生成される主なファイル

ルーティング
コントローラークラス
ビュー(テンプレートファイル)
モデルクラス
マイグレーションファイル

class BooksController < ApplicationController
  before_action :set_book, only: [:show, :edit, :update, :destroy]

  def index
    @books = Book.all
  end

  def show
  end

  def new
    @book = Book.new
  end

  def edit
  end

  def create
    @book = Book.new(book_params)

    respond_to do |format|
    #formatは、html形式、json形式を指す。
    #rake routesで確認できるURLパターンの、(.:format)部分。省略可能なので、あまり表示されない。
      if @book.save
        format.html { redirect_to @book, notice: 'Book was successfully created.' }
#@bookは、set_bookで生成されたオブジェクト。引数にオブジェクトが渡された時は、「@book.id」を示す。
        format.json { render :show, status: :created, location: @book }
      else
        format.html { render :new }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { render :show, status: :ok, location: @book }
      else
        format.html { render :edit }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    def set_book
      @book = Book.find(params[:id])
    end

    def book_params
      params.require(:book).permit(:isbn, :title, :price, :publish, :published, :dl)
    end
end

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