From 812d7a3c051b83aa4d4a3f79970a031962c179de Mon Sep 17 00:00:00 2001
From: Sylvain <bond.never.die@gmail.com>
Date: Thu, 30 Jun 2016 09:57:40 +0200
Subject: [PATCH] server-side protection against last category deletion

---
 app/controllers/api/categories_controller.rb | 7 +++++--
 app/models/category.rb                       | 8 ++++++++
 2 files changed, 13 insertions(+), 2 deletions(-)

diff --git a/app/controllers/api/categories_controller.rb b/app/controllers/api/categories_controller.rb
index a3d08caa5..e6c840c41 100644
--- a/app/controllers/api/categories_controller.rb
+++ b/app/controllers/api/categories_controller.rb
@@ -31,8 +31,11 @@ class API::CategoriesController < API::ApiController
 
   def destroy
     authorize Category
-    @category.destroy
-    head :no_content
+    if @category.safe_destroy
+      head :no_content
+    else
+      render json: @category.errors, status: :unprocessable_entity
+    end
   end
 
   private
diff --git a/app/models/category.rb b/app/models/category.rb
index 6ba887857..e812aae3b 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -1,3 +1,11 @@
 class Category < ActiveRecord::Base
   has_and_belongs_to_many :events, join_table: :events_categories, dependent: :destroy
+
+  def safe_destroy
+    if count > 1
+      destroy
+    else
+      false
+    end
+  end
 end