Skip to content

Commit

Permalink
Add error flash to resource controller (AlchemyCMS#1827)
Browse files Browse the repository at this point in the history
This adds an error flash to the resource controller if some action does
not succeed.
  • Loading branch information
mamhoff authored May 14, 2020
1 parent f25b8e5 commit 8ff8ca2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
3 changes: 3 additions & 0 deletions app/controllers/alchemy/admin/resources_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/controllers/alchemy/admin/resources_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 10 additions & 0 deletions spec/dummy/app/models/event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand All @@ -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

0 comments on commit 8ff8ca2

Please sign in to comment.