From bae09624b79b678feeb90c5ae3c3c3de43fa394f Mon Sep 17 00:00:00 2001 From: benni Date: Tue, 11 Dec 2012 10:53:01 +0100 Subject: [PATCH] Avoid deleting categories which still have articles. --- app/controllers/article_categories_controller.rb | 6 ++++++ app/models/article_category.rb | 8 ++++++++ config/locales/de.yml | 6 ++++++ 3 files changed, 20 insertions(+) diff --git a/app/controllers/article_categories_controller.rb b/app/controllers/article_categories_controller.rb index 514bf725..eb81cb1d 100644 --- a/app/controllers/article_categories_controller.rb +++ b/app/controllers/article_categories_controller.rb @@ -12,6 +12,12 @@ class ArticleCategoriesController < ApplicationController update!(:notice => "Die Kategorie wurde aktualisiert") { article_categories_path } end + def destroy + destroy! + rescue => error + redirect_to article_categories_path, alert: t('controller.article_categories.destroy.error', message: error.message) + end + protected def collection diff --git a/app/models/article_category.rb b/app/models/article_category.rb index eceb23e9..bd0e3d68 100644 --- a/app/models/article_category.rb +++ b/app/models/article_category.rb @@ -3,5 +3,13 @@ class ArticleCategory < ActiveRecord::Base validates :name, :presence => true, :uniqueness => true, :length => { :in => 2..20 } + before_destroy :check_for_associated_articles + + protected + + def check_for_associated_articles + raise I18n.t('activerecord.errors.has_many_left', collection: Article.model_name.human) if articles.exists? + end + end diff --git a/config/locales/de.yml b/config/locales/de.yml index b5a30be4..213c3c97 100644 --- a/config/locales/de.yml +++ b/config/locales/de.yml @@ -21,6 +21,11 @@ de: previous: "‹" next: "›" truncate: "..." + + controller: + article_categories: + destroy: + error: 'Kategorie konnte nicht gelöscht werden: %{message}' date: abbr_day_names: - So @@ -216,6 +221,7 @@ de: activerecord: errors: <<: *errors + has_many_left: 'ist noch mit einem/r %{collection} verknüpft!' models: article: Artikel supplier: Lieferant