diff --git a/app/controllers/api/internal/v1/mailers_controller.rb b/app/controllers/api/internal/v1/mailers_controller.rb index 8bfbe44a16..61035ea244 100644 --- a/app/controllers/api/internal/v1/mailers_controller.rb +++ b/app/controllers/api/internal/v1/mailers_controller.rb @@ -13,7 +13,7 @@ def registration requesting_user = params.require(:current_user) registration_competition = params.require(:competition_id) user = User.find(registration_user) - registration = user.microservice_registrations.find_by(competition_id: registration_competition) + registration = user.find_ms_registration_by(competition_id: registration_competition) if registration_status == 'pending' && registration_action == 'create' RegistrationsMailer.notify_organizers_of_new_registration(registration).deliver_later diff --git a/app/controllers/api/internal/v1/payment_controller.rb b/app/controllers/api/internal/v1/payment_controller.rb index e48b4711ef..94d1a43942 100644 --- a/app/controllers/api/internal/v1/payment_controller.rb +++ b/app/controllers/api/internal/v1/payment_controller.rb @@ -17,9 +17,7 @@ def init_stripe competition = Competition.find(competition_id) return render json: { error: "Competition not found" }, status: :not_found unless competition.present? - ms_registration = competition.microservice_registrations - .includes(:competition, :user) - .find_by(user_id: registering_user_id) + ms_registration = competition.find_ms_registration_by(user_id: registering_user_id) return render json: { error: "Registration not found" }, status: :not_found unless ms_registration.present? diff --git a/app/models/concerns/microservice_registration_holder.rb b/app/models/concerns/microservice_registration_holder.rb index 1db2d54b8e..1c35ca3891 100644 --- a/app/models/concerns/microservice_registration_holder.rb +++ b/app/models/concerns/microservice_registration_holder.rb @@ -42,4 +42,21 @@ def microservice_registrations end end end + + private def scoped_find_by(scope, **kwargs) + kwarg_symbols = kwargs.keys.map(&:to_sym) + own_assoc_key = self.class.model_name.element.to_sym + + preload_keys = MicroserviceRegistration.reflect_on_all_associations.filter { |assoc| + # Pick by either the name (ie. `competition`) or the foreign key (ie. `competition_id`) of the association + kwarg_symbols.include?(assoc.name.to_sym) || kwargs.keys.include?(assoc.foreign_key.to_sym) + }.map(&:name) + + scope.includes(own_assoc_key, *preload_keys) + .find_by(own_assoc_key => self, **kwargs) + end + + def find_ms_registration_by(**) + self.scoped_find_by(MicroserviceRegistration, **) || self.scoped_find_by(self.microservice_registrations, **) + end end