学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails導入編 | カート機能の実装 | 08 | 商品リストの外観を整える

↓↓クリックして頂けると励みになります。




07 | 商品の登録】 << 【ホーム】 >> 【09 | バリデーション(検証)



商品リストを見栄えの良いものに変更してみます。
3個程度、商品を登録しておいて下さい。

コントローラー



「SampleCart/app/controllers/goods_controller.rb」ファイルの内容を見てみます。
indexメソッドに@goods = Good.allの記述があります。
これによりindexビューで@goodsを利用することができます。
Good.allは、Goodテーブルに格納されているデータ全てという意味です。


記述確認 【SampleCart/app/controllers/goods_controller.rb】

class GoodsController < ApplicationController
  before_action :set_good, only: %i[ show edit update destroy ]

  # GET /goods or /goods.json
  def index
    @goods = Good.all
  end

  # GET /goods/1 or /goods/1.json
  def show
  end

  # GET /goods/new
  def new
    @good = Good.new
  end

  # GET /goods/1/edit
  def edit
  end

  # POST /goods or /goods.json
  def create
    @good = Good.new(good_params)

    respond_to do |format|
      if @good.save
        format.html { redirect_to good_url(@good), notice: "Good was successfully created." }
        format.json { render :show, status: :created, location: @good }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @good.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /goods/1 or /goods/1.json
  def update
    respond_to do |format|
      if @good.update(good_params)
        format.html { redirect_to good_url(@good), notice: "Good was successfully updated." }
        format.json { render :show, status: :ok, location: @good }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @good.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /goods/1 or /goods/1.json
  def destroy
    @good.destroy!

    respond_to do |format|
      format.html { redirect_to goods_url, notice: "Good was successfully destroyed." }
      format.json { head :no_content }
    end
  end

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

    # Only allow a list of trusted parameters through.
    def good_params
      params.require(:good).permit(:goods_id, :title, :description, :image_url, :price, :date, :maker, :category)
    end
end


ビュー

実際にビューを編集します。
「SampleCart/app/views/goods/index.html.erb」ファイルを以下のように編集します。


記述編集 【SampleCart/app/views/goods/index.html.erb】

<p style="color: green"><%= notice %></p>

<div class="container">
  <div class="h2">お取り扱い商品</div>
  <div class="mb-4 mt-4">
    <%= link_to "新しい商品を登録", new_good_path, class: "btn btn-danger" %>
  </div>

  <div id="goods">
    <div class="row">
      <% @goods.each do |good| %>
        <div class="col-md-4">
          <%= render good %>
        </div>
      <% end %>
    </div>
  </div>
</div>



続いてレンダーファイル「SampleCart/app/views/goods/_good.html.erb」を以下のように編集します。


記述編集 【SampleCart/app/views/goods/_good.html.erb】

<div id="<%= dom_id good %>">

  <div class="card">
    <img src="<%= good.image_url %>" class="card-img-top" style="width: 100%; height: 200px; object-fit: cover;">
    <div class="card-body">
      <p>
        <strong>Goods:</strong>
        <%= good.goods_id %>
      </p>
      <p>
        <strong>Title:</strong>
        <%= good.title %>
      </p>
      <p>
        <strong>Description:</strong>
        <%= good.description %>
      </p>
      <p>
        <strong>Price:</strong>
        <%= good.price %>
      </p>
      <p>
        <strong>Date:</strong>
        <%= good.date %>
      </p>
      <p>
        <strong>Maker:</strong>
        <%= good.maker %>
      </p>
      <p>
        <strong>Category:</strong>
        <%= good.category %>
      </p>
      <p>
        <%= link_to "この商品の詳細", good, class: "btn btn-success" %>
      </p>
    </div>
  </div>

</div>



こうすることで、商品リストページのレイアウトが以下のように変更されました。
ブラウザを更新して確認して下さい。
http://localhost:3000/goods

商品リストページ更新
商品リストページ更新



レンダーファイル「_good.html.erb」の4行目にstyle=""としてCSSの記述を直接書きました。
Railsでは、SCSSファイルにCSSを記述するこで、ビューの記述をスリムにすることができます。
まずはレンダーファイル「_good.html.erb」の4行目の記述からstyle=""の記述を削除します。
そうすると、当然ですがレイアウトが崩れます。

画像のレイアウトが崩れる
画像のレイアウトが崩れる



次に「SampleCart/app/assets/stylesheets/application.scss」ファイルにCSSの記述を追加します。


記述追加 【SampleCart/app/assets/stylesheets/application.scss】19行目

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */

 @import "bootstrap";

.card-img-top {
    width: 100%;
    height: 200px;
    object-fit: cover;
}



ページを更新すると、スタイルが適用されているのが分かります。

スタイル適用
スタイル適用




07 | 商品の登録】 << 【ホーム】 >> 【09 | バリデーション(検証)





↓↓クリックして頂けると励みになります。