diff --git a/app/controllers/admin/vouchers_controller.rb b/app/controllers/admin/vouchers_controller.rb index 6a73bd7787..33093bb07d 100644 --- a/app/controllers/admin/vouchers_controller.rb +++ b/app/controllers/admin/vouchers_controller.rb @@ -9,20 +9,9 @@ module Admin end def create - # In the scenario where you get an error when trying to create a percentage voucher, we'll - # now have percentage rate voucher instanciated. Hence why we check for both params type - voucher_type = params.dig(:voucher, :voucher_type) - - # The use of "safe_constantize" here will trigger a Brakeman error, it can safely be ignored - # as it's a false positive : https://github.com/openfoodfoundation/openfoodnetwork/pull/10821 - if Voucher::TYPES.include?(voucher_type) - @voucher = voucher_type.safe_constantize.create( - permitted_resource_params.merge(enterprise: @enterprise) - ) - else - @voucher.errors.add(:type) - return render_error - end + @voucher = Voucher.new( + permitted_resource_params.merge(enterprise: @enterprise) + ) if @voucher.save flash[:success] = I18n.t(:successfully_created, resource: "Voucher") @@ -30,6 +19,9 @@ module Admin else render_error end + rescue ActiveRecord::SubclassNotFound + @voucher.errors.add(:type) + render_error end private @@ -47,7 +39,7 @@ module Admin end def permitted_resource_params - params.require(:voucher).permit(:code, :amount) + params.require(:voucher).permit(:code, :amount, :type) end end end diff --git a/app/views/admin/vouchers/new.html.haml b/app/views/admin/vouchers/new.html.haml index 77eff6d903..de23acf867 100644 --- a/app/views/admin/vouchers/new.html.haml +++ b/app/views/admin/vouchers/new.html.haml @@ -17,9 +17,9 @@ = f.text_field :code, class: 'fullwidth' .row .alpha.four.columns - = f.label :voucher_type, t('.voucher_type') + = f.label :type, t('.voucher_type') .omega.eight.columns - = f.select :voucher_type, options_for_select(Voucher::TYPES.map { |type| [t(".#{type.demodulize.underscore}"), type] }, @voucher.class.to_s) + = f.select :type, options_for_select(Voucher::TYPES.map { |type| [t(".#{type.demodulize.underscore}"), type] }, @voucher.class.to_s) .row .alpha.four.columns = f.label :amount, t('.voucher_amount') diff --git a/spec/requests/admin/vouchers_controller_spec.rb b/spec/requests/admin/vouchers_controller_spec.rb index 04e4c001c5..80a6ca78fc 100644 --- a/spec/requests/admin/vouchers_controller_spec.rb +++ b/spec/requests/admin/vouchers_controller_spec.rb @@ -29,7 +29,7 @@ describe Admin::VouchersController, type: :request do voucher: { code: code, amount: amount, - voucher_type: type + type: type } } end @@ -55,7 +55,7 @@ describe Admin::VouchersController, type: :request do voucher: { code: code, amount: amount, - voucher_type: type + type: type } } end