From c22a80b48ff458e1490992fd62189dff45d54785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alberto=20Miedes=20Garc=C3=A9s?= Date: Tue, 13 Dec 2016 12:30:47 +0100 Subject: [PATCH] Move geozone 'safe to destroy' check from controller to model --- app/controllers/admin/geozones_controller.rb | 13 ++----------- app/models/geozone.rb | 5 +++++ 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/app/controllers/admin/geozones_controller.rb b/app/controllers/admin/geozones_controller.rb index a8648f287..b73c13422 100644 --- a/app/controllers/admin/geozones_controller.rb +++ b/app/controllers/admin/geozones_controller.rb @@ -33,18 +33,9 @@ class Admin::GeozonesController < Admin::BaseController end def destroy - # Check that in none of the other associated models tables a record exists - # referencing this geozone - safe_to_destroy = true - - Geozone.reflect_on_all_associations.each do |association| - attached_model = association.klass - safe_to_destroy &= attached_model.where(geozone: @geozone).empty? - end - - if safe_to_destroy + if @geozone.safe_to_destroy? @geozone.destroy - redirect_to admin_geozones_url, notice: t('admin.geozones.delete.success') + redirect_to admin_geozones_path, notice: t('admin.geozones.delete.success') else redirect_to admin_geozones_path, flash: { error: t('admin.geozones.delete.error') } end diff --git a/app/models/geozone.rb b/app/models/geozone.rb index 0dc0e38d6..7e38ce97d 100644 --- a/app/models/geozone.rb +++ b/app/models/geozone.rb @@ -9,4 +9,9 @@ class Geozone < ActiveRecord::Base Geozone.pluck(:name) end + def safe_to_destroy? + Geozone.reflect_on_all_associations(:has_many).all? do |association| + association.klass.where(geozone: self).empty? + end + end end