Skip to content

Commit

Permalink
jobの検索ロジックをcontrollerからmodelに移行
Browse files Browse the repository at this point in the history
  • Loading branch information
reckyy committed Mar 29, 2024
1 parent 8a7f231 commit 77e8fa0
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
8 changes: 1 addition & 7 deletions app/controllers/admin/users_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,13 @@
class Admin::UsersController < AdminController
before_action :set_user, only: %i[show edit update]
ALLOWED_TARGETS = %w[all student_and_trainee inactive hibernated retired graduate adviser mentor trainee year_end_party campaign].freeze
ALLOWED_JOBS = User.jobs.keys.prepend('all').freeze

def index
@direction = params[:direction] || 'desc'
@target = params[:target]
@job = params[:job]
user_scope = User.users_role(@target, allowed_targets: ALLOWED_TARGETS, default_target: 'student_and_trainee')
# User::users_roleと同じく安全性確保のため、以下の条件を指定している。
# ALLOWED_JOBS.include?(@job): 存在する職業を過不足なく指定した配列の中に、params[:job]が存在するかどうかチェック。
if @job.present? && ALLOWED_JOBS.include?(@job)
scoped_job = @job == 'all' ? @job : "job_#{@job}"
user_scope = user_scope.public_send(scoped_job)
end
user_scope = user_scope.users_job(@job) if @job.present?
@users = user_scope.with_attached_avatar
.preload(:company, :course)
.order_by_counts(params[:order_by] || 'id', @direction)
Expand Down
8 changes: 8 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,14 @@ def users_role(target, allowed_targets: [], default_target: :none)
send(scope_name)
end

# User::users_roleと同じく安全性確保のため、以下の条件を指定している。
# allowed_job.include?(job): 存在する職業を過不足なく指定した配列の中に、jobが存在するかどうかチェック。
def users_job(job)
allowed_jobs = User.jobs.keys.freeze
scope_name = allowed_jobs.include?(job) ? "job_#{job}" : 'all'
send(scope_name)
end

def tags
unretired.unhibernated.all_tag_counts(order: 'count desc, name asc')
end
Expand Down
12 changes: 12 additions & 0 deletions test/models/user_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -724,4 +724,16 @@ class UserTest < ActiveSupport::TestCase
assert_equal '2020-07-01 09:00:00 +0900', users(:kyuukai).scheduled_retire_at.to_s
assert_nil users(:hatsuno).scheduled_retire_at
end

test '.users_job' do
assert_equal User.job_student, User.users_job('student')
assert_equal User.job_office_worker, User.users_job('office_worker')
assert_equal User.job_part_time_worker, User.users_job('part_time_worker')
assert_equal User.job_vacation, User.users_job('vacation')
assert_equal User.job_unemployed, User.users_job('unemployed')
end

test '.users_job returns all users when invalid job is passed' do
assert_equal User.all, User.users_job('destroy_all')
end
end

0 comments on commit 77e8fa0

Please sign in to comment.