2020-03-25 17:45:53 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# Category is a first-level filter, used to categorize Events.
|
|
|
|
# It is mandatory to choose a Category when creating an event.
|
2020-03-25 10:16:47 +01:00
|
|
|
class Category < ApplicationRecord
|
2016-06-30 11:24:57 +02:00
|
|
|
extend FriendlyId
|
|
|
|
friendly_id :name, use: :slugged
|
|
|
|
|
2016-07-25 16:16:25 +02:00
|
|
|
has_many :events, dependent: :destroy
|
2016-06-30 09:57:40 +02:00
|
|
|
|
2016-06-30 11:24:57 +02:00
|
|
|
after_create :create_statistic_subtype
|
2020-03-24 16:45:27 +01:00
|
|
|
after_update :update_statistic_subtype, if: :saved_change_to_name?
|
2016-06-30 11:24:57 +02:00
|
|
|
after_destroy :remove_statistic_subtype
|
|
|
|
|
|
|
|
|
|
|
|
def create_statistic_subtype
|
|
|
|
index = StatisticIndex.where(es_type_key: 'event')
|
2018-12-03 15:10:04 +01:00
|
|
|
StatisticSubType.create!(statistic_types: index.first.statistic_types, key: slug, label: name)
|
2016-06-30 11:24:57 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def update_statistic_subtype
|
|
|
|
index = StatisticIndex.where(es_type_key: 'event')
|
2018-12-03 15:10:04 +01:00
|
|
|
subtype = StatisticSubType.joins(statistic_type_sub_types: :statistic_type)
|
|
|
|
.where(key: slug, statistic_types: { statistic_index_id: index.first.id })
|
|
|
|
.first
|
|
|
|
subtype.label = name
|
2016-06-30 11:24:57 +02:00
|
|
|
subtype.save!
|
|
|
|
end
|
|
|
|
|
|
|
|
def remove_statistic_subtype
|
2018-12-03 15:10:04 +01:00
|
|
|
subtype = StatisticSubType.where(key: slug).first
|
2016-06-30 11:24:57 +02:00
|
|
|
subtype.destroy!
|
|
|
|
end
|
|
|
|
|
2016-06-30 09:57:40 +02:00
|
|
|
def safe_destroy
|
2018-12-03 15:10:04 +01:00
|
|
|
if Category.count > 1 && events.count.zero?
|
2016-06-30 09:57:40 +02:00
|
|
|
destroy
|
|
|
|
else
|
|
|
|
false
|
|
|
|
end
|
|
|
|
end
|
2015-05-05 03:10:25 +02:00
|
|
|
end
|