LoginSignup
1
0

管理者側 顧客一覧ページ

Posted at

:shamrock: migrageファイル追加

まず、モデルに退会ステータスのためのフィールドを追加します。今回は、boolean型is_deletedというカラムを追加することにします。

 t.boolean "is_deleted", default: false

:star:boolean型 のis_deletedがなければ
ターミナルで以下のコマンドを実行します

rails generate migration add_is_deleted_to_customers is_deleted:boolean
rails db:migrate

:shamrock:コントローラー

abmin/customers.html.rb
class Admin::CustomersController < ApplicationController
  def index
    @customers = Customer.all
  end
end

:shamrock:views 顧客一覧ページ

admin/costomers/index.html.erb
<div class="container">
  <div class="row">
    <h2>会員一覧</h2>

      <table class="table">
        <thead>
        <tr>
          <th>会員ID</th>
          <th>氏名</th>
          <th>メールアドレス</th>
          <th>ステータス</th>
        </tr>
      </thead>
        <% @customers.each do |customer| %>
          <tr>
            <td><%= customer.id %></td>
            <td><%= customer.first_name %> <%= customer.last_name %></td>
            <td><%= customer.email %></td>
           <td class="<%= customer.is_deleted ? 'text-gray' : 'text-green' %>"><%= customer.is_deleted ? '退会済み' : '有効' %></td>
          </tr>
        <% end %>
      </table>
    </div>
  </div>

補足

Customerモデルにnameメソッド(nameフィールドを指しています)が存在しないことがわかります。これは、Customerモデルにnameというフィールドが存在しないからです。
スクリーンショット 2023-07-20 17.58.10.png
ですので、以下のコマンドを実行してカラムを追加します。

rails generate migration add_name_to_customers name:string
rails db:migrate
 create_table "customers", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.boolean "is_deleted", default: false
+   t.string "name"
    t.index ["email"], name: "index_customers_on_email", unique: true
    t.index ["reset_password_token"], name: "index_customers_on_reset_password_token", unique: true
  end

:cherry_blossom:しかし、今回はnameカラムは必要ありませんでした(笑)
以下のコマンドで削除しました。

rails generate migration RemoveNameFromCustomers name:string

これで新しいマイグレーションファイルが生成されます。生成されたマイグレーションファイルを開き、内容が次のようになっていることを確認します

class RemoveNameFromCustomers < ActiveRecord::Migration[6.1]
  def change
    remove_column :customers, :name, :string
  end
end
rails db:migrate

:point_up:理由は顧客新規登録ページにあります!

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