プログラミング備忘録

プログラミングメモ

Ruby・Rails

Ruby on Railsのscaffoldの使い方・作成されるファイルなどを解説

scaffold

 

今回は「Ruby on Railsのscaffoldの使い方」について解説します。

scaffoldを使うことで簡単に機能の雛形を作成することができるので、ぜひ使ってみてください。

 

 

Ruby on Railsのscaffoldの使い方の手順

まず初めにRuby on Railsのscaffoldの使い方の説明をします。

Railsアプリケーションの作成


rails new blog

まずは「rails new アプリケーション名」を実行して、アプリケーションを作成してください。
今回は例としてブログの投稿管理機能を作成するので「blog」にしています。

 

 

作成したアプリケーションのディレクトリに移動


cd blog

ディレクトリの移動を行ってください。

 

 

rails g scaffoldを実行する


rails g scaffold Post title:string content:text

ここで今回の主人公である「rails g scaffold」を実行します。

今回はカラムを2つ用意しました。「string型のtitle」と「text型のcontent」です。
もし複数のカラムのテーブルを作りたいときは「カラム名:データ型」を複数書いてください。

rails g scaffold

「rails g scaffold」で作成されるファイル

 

 

マイグレーションファイルをデータベースに反映させる


rails db:migrate

「rails g scaffold」を実行したときに、マイグレーションファイルも一緒に作成されます。
その作成されたマイグレーションファイルをデータベースに反映させるために「rails db:migrate」を実行してください。

 

 

scaffoldを使用した雛形の完成

これまでの手順を行うことで、「scaffold」を使用した投稿機能の雛形が完成しました。


rails s

サーバーを起動して、ブラウザのアドレスバーに「ドメイン/posts」と入力してみてください。

以下のような画面が表示されていれば、実装できています。

scaffold 画面

「rails g scaffold」で実装された画面

 

 

Ruby on Railsのscaffoldで作成されるファイル

この章では「scaffold」で作成されるファイルを紹介していきます。
先ほどの画像と同じものですが、これらが作成されるファイルです。

rails g scaffold

それでは解説していきます。

 

 

マイグレーションファイル


class CreatePosts < ActiveRecord::Migration[5.2]
 def change
  create_table :posts do |t|
   t.string :title
   t.text :content

   t.timestamps
  end
 end
end

データベースの元になるマイグレーションファイルが作成されます。

 

モデル


class Post < ApplicationRecord
end

モデルが作成されます。

 

ルーティング


resources :posts

「routes.rb」に「resources :posts」が追記されます。

 

 

コントローラ


class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end

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

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Only allow a list of trusted parameters through.
    def post_params
      params.require(:post).permit(:title, :content)
    end
end

コントローラファイルが作成されます。
既に必要なアクションは自動的に定義されています。

 

 

 

 

ビュー


<p id="notice"><%= notice %></p>

<h1>Posts</h1>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td><%= post.content %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Post', new_post_path %>



<h1>Editing Post</h1>

<%= render 'form', post: @post %>

<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>


<p id="notice"><%= notice %></p>

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<p>
  <strong>Content:</strong>
  <%= @post.content %>
</p>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>


<h1>New Post</h1>

<%= render 'form', post: @post %>

<%= link_to 'Back', posts_path %>


<%= form_with(model: post, local: true) do |form| %>
  <% if post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>

  <div class="field">
    <%= form.label :content %>
    <%= form.text_area :content %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

上記の5つのビューファイルが自動で作成されます。

 

 

まとめ

今回はscaffoldの使い方について解説しました。

ルーティングから、コントローラ、ビューまで、自動で生成してくれるので、何か管理機能のようなものを作りたいときに便利ですので、ぜひ活用してみてください。

-Ruby・Rails

Copyright© プログラミングメモ , 2024 All Rights Reserved Powered by AFFINGER5.