LoginSignup
0
0

【Ruby on rails】絞り込み表示機能

Last updated at Posted at 2023-11-11

はじめに

プログラミングを勉強して3か月ほどです。
プログラミングスクールを卒業し、現在就職活動をしています。

今回はオリジナルアプリの在庫管理アプリで絞り込み表示機能を実装したので共有したいと思います。
以下のような感じで在庫が不足しているアイテムのみを表示します。

Image from Gyazo

※初心者なので間違っているところがあれば、ご指摘いただけると幸いです。

Let's start!!!

モデルとコントローラーの作成

今回はitemモデルとitemsコントローラーを作成します。
rails g model item
rails g controller items

マイグレーションファイルの中身

2023xxxxxxxxx_create_items.rb
class CreateItems < ActiveRecord::Migration[7.0]
  def change
    create_table :items do |t|
      t.string :name, null: false
      t.string :storage
      t.integer :quantity, null: false
      t.integer :lower, null: false
      t.text :explanation
      t.string :pdf
      t.boolean :taking, default: false, null: false
      t.references :user,  foreign_key: true
      t.references :group, foreign_key: true

      t.timestamps
    end
  end
end

色々書かれていますが、今回必要なものはquantitylowerの2つのカラムです。
quantityが数量を保存するカラム、lowerが下限数量を保存するカラムです。
lowerquantityを下回った時が在庫が不足している状態になります。
記述ができたらマイグレートしましょう。
rails db:migrate

ルーティングの設定

routes.rb
Rails.application.routes.draw do
  devise_for :users
  root to: "groups#index"
  resources :groups do
    get "join" => "groups#join"
    delete "exit" => "groups#exit"
    post "invitation" => "groups#invitation"
    delete "cancel" => "groups#cancel"
    resources :items do
      collection do
        get 'search'
        get "shortage" #ここを記述
      end
      get "use" => "items#use"
      get "back" => "items#back"
    end
  end
  resources :notifications, only: :index
  resources :welcomes, only: :index
end

shortageアクションを追加します。
在庫不足アイテムを一覧で表示するだけなのでidまで取得する必要がありません。
なので今回はcollectionを用いてルーティングを設定しています。
※私のアプリの場合はグループの中にネストしているので上記のような記述になります。

モデルの記述

item.rb
class Item < ApplicationRecord

  def self.shortage
    Item.where("lower > quantity")
  end

end

Item.where("lower > quantity")
itemsテーブルのlowerquantityよりも大きいレコードを抽出しています。

コントローラーの記述

items.controller.rb
class ItemsController < ApplicationController

  def index
    @item = Item.new
    @group = Group.find(params[:group_id])
    @items = @group.items.includes(:user)
  end

  # 中略

  def shortage
    @group = Group.find(params[:group_id])
    @items = @group.items.shortage
    render :index
  end

end

※今回は必要なアクション部分のみ抜き出しています。

@items = @group.items.shortageの記述で在庫が不足しているアイテムを表示させます。
モデルに記述したshortageメソッドを使用することで在庫不足アイテムを抽出することができます。

終わりに

みなさん実装お疲れさまでした!
今回は絞り込み表示機能について共有させていただきました。
みなさんのお役に立てていれば幸いです。

最後まで読んでいただきありがとうございました!!!

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