以下のようなハッシュを画面に返すとする。
# 画面に引き渡すインスタンス変数(Hash) # @conpany_inf カンパニー情報(ヘッダ情報) # { # company_name [string] カンパニー名 # company_started_at [datetime] 創設日 # staff_count [integer] スタッフ人数 # } # @staff_inf スタッフ一覧情報 # [{ # staff_no: [string] スタッフNO # staff_name: [string] スタッフ名 # staff_class: [string] 一般職/管理職 # license_info: 資格情報 # [{ # license_name [string] 資格名 # license_get_date [datetime] 取得日 # }] # }]
各モデルは以下のようなイメージ。
# app/model/company.rb class Company < ApplicationRecord has_many :staffs end # app/model/staff.rb class Staff < ApplicationRecord belong_to :company has_many :licenses scope :alive, -> { where(is_retire: false) } scope :manage_alive, -> { alive.where(is_manage: true) } end # app/model/license.rb class License < ApplicationRecord end
コントローラは以下のようなロジックで実装。
# controller/staff_controller.rb class StaffController < ApplicationController # 画面に引き渡すインスタンス変数(Hash) # @conpany_inf カンパニー情報(ヘッダ情報) # { # company_name [string] カンパニー名 # company_started_at [datetime] 創設日 # staff_count [integer] スタッフ人数 # } # @staff_inf スタッフ一覧情報 # [{ # staff_no: [string] スタッフNO # staff_name: [string] スタッフ名 # staff_class: [string] 一般職/管理職 # license_info: 資格情報 # [{ # license_name [string] 資格名 # license_get_date [datetime] 取得日 # }] # }] def index @conpany_inf = conpany_inf_rec(company) @staff_inf = [] staffs = company.staffs.order(:staff_no).alive staffs.each do |s| @staff_inf << staff_inf_rec(s) end end private def company @company ||= Company.find(params[:id]) end def conpany_inf_rec(company) { company_name: company&.name company_started_at: company.&.started_at staff_count: company.staffs.count } end def staff_inf_rec(staff) { staff_no: staff&.staff_no staff_name: staff&.name staff_class: staff&.is_manage_lank & 'manage' : 'normal' license_info: license_info_rec(staff) } end def license_info_rec(staff) staff.licenses.order(:get_date).map do |li| { license_name: li.name license_get_date: li.get_date } end end end