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

68 lines
1.5 KiB
Ruby
Raw 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-09-30 18:20:45 -04:00
presence: {
if: ->(record) { record.kind&.parent_kind },
message: :required,
}
2019-09-30 19:32:04 -04:00
2019-10-21 03:15:08 -04:00
validates :resource,
presence: {
if: ->(record) { record.kind&.resource_type },
message: :required,
}
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-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 = parent_unit.nil? ? 0 : parent_unit.level + 1
2019-09-30 19:32:04 -04:00
end
2019-09-30 18:20:45 -04:00
end