From 8ff8ca28854ceefe8f56825c22124fc08bfe3ce0 Mon Sep 17 00:00:00 2001 From: Martin Meyerhoff Date: Thu, 14 May 2020 14:23:52 +0200 Subject: [PATCH] Add error flash to resource controller (#1827) This adds an error flash to the resource controller if some action does not succeed. --- app/controllers/alchemy/admin/resources_controller.rb | 3 +++ .../alchemy/admin/resources_controller_spec.rb | 11 +++++++++++ spec/dummy/app/models/event.rb | 10 ++++++++++ 3 files changed, 24 insertions(+) diff --git a/app/controllers/alchemy/admin/resources_controller.rb b/app/controllers/alchemy/admin/resources_controller.rb index bff8b29a8c..4bbf962c89 100644 --- a/app/controllers/alchemy/admin/resources_controller.rb +++ b/app/controllers/alchemy/admin/resources_controller.rb @@ -79,6 +79,9 @@ def update def destroy resource_instance_variable.destroy + if resource_instance_variable.errors.any? + flash[:error] = resource_instance_variable.errors.full_messages.join(", ") + end flash_notice_for_resource_action do_redirect_to resource_url_proxy.url_for(search_filter_params.merge(action: "index")) end diff --git a/spec/controllers/alchemy/admin/resources_controller_spec.rb b/spec/controllers/alchemy/admin/resources_controller_spec.rb index 535f84aa75..349e6d4096 100644 --- a/spec/controllers/alchemy/admin/resources_controller_spec.rb +++ b/spec/controllers/alchemy/admin/resources_controller_spec.rb @@ -137,5 +137,16 @@ def resource_handler delete :destroy, params: {id: peter.id}.merge(params) expect(response.redirect_url).to eq("http://test.host/admin/events?page=6&q%5Bname_or_hidden_name_or_description_or_location_name_cont%5D=some_query") end + + context "If the resource is not destroyable" do + let!(:undestroyable) { create(:event, name: "Undestructible") } + + it "adds an error flash" do + delete :destroy, params: {id: undestroyable.id}.merge(params) + + expect(response.redirect_url).to eq("http://test.host/admin/events?page=6&q%5Bname_or_hidden_name_or_description_or_location_name_cont%5D=some_query") + expect(flash[:error]).to eq("This is the undestructible event!") + end + end end end diff --git a/spec/dummy/app/models/event.rb b/spec/dummy/app/models/event.rb index 2b76472b76..51ce96545c 100644 --- a/spec/dummy/app/models/event.rb +++ b/spec/dummy/app/models/event.rb @@ -5,6 +5,7 @@ class Event < ActiveRecord::Base validates_presence_of :name belongs_to :location + before_destroy :abort_if_name_is_undestructible scope :starting_today, -> { where(starts_at: Time.current.at_midnight..Date.tomorrow.at_midnight) } scope :future, -> { where("starts_at > ?", Date.tomorrow.at_midnight) } @@ -18,4 +19,13 @@ def self.alchemy_resource_relations def self.alchemy_resource_filters %w(starting_today future) end + + private + + def abort_if_name_is_undestructible + if name == "Undestructible" + errors.add(:base, "This is the undestructible event!") + throw(:abort) + end + end end