LoginSignup
0
0

条件に合う配列のみをプルダウンに表示する方法

Posted at

Railsで関連付けられたレコードの一部だけをフォームのセレクトボックスに表示する方法を紹介します。この例では、Company が複数の Staff を持ち、StaffSchedule と関連付けられています。特定の日に勤務している(at_work カラムが true)スタッフのみをプルダウンに表示します。

モデルの関連付け

まず、Company モデルと Staff モデル、Schedule モデルの間には以下のような関連付けが定義されているとします。

class Company < ApplicationRecord
  has_many :staffs
end

class Staff < ApplicationRecord
  belongs_to :company
  has_many :schedules
end

class Schedule < ApplicationRecord
  belongs_to :staff
end

Company モデルでのメソッド定義

特定の日に勤務しているスタッフを取得するために、Company モデルにメソッドを定義します。

class Company < ApplicationRecord
  has_many :staffs

  # 勤務しているスタッフのみを取得するメソッド
  def working_staffs(date)
    staffs.joins(:schedules).where(schedules: { date: date, at_work: true })
  end
end

コントローラーでのデータ取得

コントローラーでは、@working_staffs を設定して、ビューで使用できるようにします。

class SchedulesController < ApplicationController
  def quota_index
    @reservation = Reservation.find(params[:reservation_id])
    @working_staffs = @company.working_staffs(@reservation.date)
  end
end

ビューでのプルダウンの設定

ビューでは、form_with ヘルパーを使用してフォームを作成し、collection_select ヘルパーで @working_staffs をセレクトボックスに表示します。

<%= form_with model: some_model, local: true do |form| %>
  <%= form.collection_select :staff_id, @working_staffs, :id, :name, {include_blank: true}, {id: 'staff_select'} %>
<% 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