1
0
Fork 0
This repository has been archived on 2023-03-27. You can view files and clone it, but cannot push or open issues or pull requests.
lpr-partynest/app/models/org_unit.rb

80 lines
1.7 KiB
Ruby
Raw Permalink Normal View History

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
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