2019-09-30 18:20:45 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class OrgUnit < ApplicationRecord
|
|
|
|
################
|
|
|
|
# Associations #
|
|
|
|
################
|
|
|
|
|
|
|
|
belongs_to :kind,
|
|
|
|
class_name: 'OrgUnitKind',
|
|
|
|
inverse_of: :instances
|
|
|
|
|
2019-10-01 21:31:12 -04:00
|
|
|
belongs_to :parent_unit,
|
2019-09-30 18:20:45 -04:00
|
|
|
class_name: 'OrgUnit',
|
2019-10-01 21:31:12 -04:00
|
|
|
inverse_of: :children_units,
|
2019-09-30 18:20:45 -04:00
|
|
|
optional: true
|
|
|
|
|
2019-10-21 03:15:08 -04:00
|
|
|
belongs_to :resource,
|
|
|
|
polymorphic: true,
|
|
|
|
optional: true
|
|
|
|
|
2019-10-01 21:31:12 -04:00
|
|
|
has_many :children_units,
|
2019-09-30 18:20:45 -04:00
|
|
|
class_name: 'OrgUnit',
|
2019-10-01 21:31:12 -04:00
|
|
|
inverse_of: :parent_unit,
|
|
|
|
foreign_key: :parent_unit_id
|
2019-09-30 18:20:45 -04:00
|
|
|
|
2019-09-30 22:30:04 -04:00
|
|
|
has_many :all_relationships,
|
|
|
|
class_name: 'Relationship',
|
|
|
|
inverse_of: :org_unit
|
|
|
|
|
2019-09-30 18:20:45 -04:00
|
|
|
###############
|
|
|
|
# Validations #
|
|
|
|
###############
|
|
|
|
|
2019-09-30 18:32:04 -04:00
|
|
|
validates :short_name, good_small_text: true, uniqueness: true
|
|
|
|
|
2019-09-30 18:20:45 -04:00
|
|
|
validates :name, good_small_text: true, uniqueness: true
|
|
|
|
|
2019-10-01 21:31:12 -04:00
|
|
|
validates :parent_unit,
|
2019-10-21 03:22:47 -04:00
|
|
|
presence: { if: :requires_parent?, message: :required },
|
|
|
|
absence: { unless: :requires_parent? }
|
2019-09-30 19:32:04 -04:00
|
|
|
|
2019-10-21 03:15:08 -04:00
|
|
|
validates :resource,
|
2019-10-21 03:25:52 -04:00
|
|
|
presence: { if: :requires_resource?, message: :required },
|
|
|
|
absence: { unless: :requires_resource? }
|
2019-10-21 03:15:08 -04:00
|
|
|
|
2019-09-30 19:32:04 -04:00
|
|
|
validate :parent_matches_kind
|
|
|
|
|
2019-10-01 21:31:12 -04:00
|
|
|
#############
|
|
|
|
# Callbacks #
|
|
|
|
#############
|
|
|
|
|
|
|
|
before_validation :set_level
|
|
|
|
|
2019-10-21 03:22:47 -04:00
|
|
|
###########
|
|
|
|
# Methods #
|
|
|
|
###########
|
|
|
|
|
|
|
|
def requires_parent?
|
|
|
|
kind&.parent_kind
|
|
|
|
end
|
|
|
|
|
2019-10-21 03:25:52 -04:00
|
|
|
def requires_resource?
|
|
|
|
kind&.resource_type
|
|
|
|
end
|
|
|
|
|
2019-09-30 19:32:04 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def parent_matches_kind
|
2019-10-01 21:31:12 -04:00
|
|
|
errors.add :parent_unit unless parent_unit&.kind == kind&.parent_kind
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_level
|
2019-10-21 03:19:53 -04:00
|
|
|
self.level =
|
|
|
|
if parent_unit.nil? then 0
|
|
|
|
elsif parent_unit.level.nil? then nil
|
|
|
|
else parent_unit.level + 1
|
|
|
|
end
|
2019-09-30 19:32:04 -04:00
|
|
|
end
|
2019-09-30 18:20:45 -04:00
|
|
|
end
|