diff --git a/app/controllers/instruction/authorizations_controller.rb b/app/controllers/instruction/authorizations_controller.rb index daf3149d3..750610979 100644 --- a/app/controllers/instruction/authorizations_controller.rb +++ b/app/controllers/instruction/authorizations_controller.rb @@ -2,7 +2,11 @@ class Instruction::AuthorizationsController < Instruction::AbstractAuthorization def index authorize [:instruction, @authorization_request], :show? - @authorizations = AuthorizationRequest.find(params[:authorization_request_id]).authorizations.order(created_at: :desc) + @authorizations = AuthorizationRequest + .find(params[:authorization_request_id]) + .authorizations + .includes(:approving_instructor) + .order(created_at: :desc) end private diff --git a/app/models/authorization.rb b/app/models/authorization.rb index cdb44c1dd..1bc59f7eb 100644 --- a/app/models/authorization.rb +++ b/app/models/authorization.rb @@ -26,6 +26,16 @@ class Authorization < ApplicationRecord as: :entity, dependent: :nullify + has_one :approve_authorization_request_event, + -> { where(name: 'approve').order(created_at: :desc).limit(1) }, + dependent: :nullify, + class_name: 'AuthorizationRequestEvent', + inverse_of: :entity + + has_one :approving_instructor, + through: :approve_authorization_request_event, + source: :user + scope :validated, -> { joins(:request).where(authorization_requests: { state: 'validated' }) } delegate :name, :kind, to: :request @@ -68,14 +78,6 @@ def definition authorization_request_class.constantize.definition end - def approving_instructor - authorization_request_events - .where(name: 'approve') - .order(created_at: :desc) - .first - .try(:user) - end - private def affect_snapshot_documents(request_as_validated) diff --git a/spec/models/authorization_spec.rb b/spec/models/authorization_spec.rb index 548251b80..e038ecb4c 100644 --- a/spec/models/authorization_spec.rb +++ b/spec/models/authorization_spec.rb @@ -96,4 +96,30 @@ end end end + + describe '#approving_instructor' do + subject { authorization.approving_instructor } + + let!(:authorization) { create(:authorization) } + + context 'when there is no approving instructor' do + it { is_expected.to be_nil } + end + + context 'when there is an approve event' do + let!(:event) { create(:authorization_request_event, entity: authorization, name: 'approve') } + + it { is_expected.to eq(event.user) } + end + + context 'when there is several approve events' do + let!(:events) do + create_list(:authorization_request_event, 3, entity: authorization, name: 'approve') do |event, index| + event.update(created_at: Time.zone.now - index.days) + end + end + + it { is_expected.to eq(events.first.user) } + end + end end