Skip to content
Snippets Groups Projects
heading.rb 1.68 KiB
Newer Older
Arnaud Levy's avatar
Arnaud Levy committed
# == Schema Information
#
# Table name: communication_block_headings
#
#  id            :uuid             not null, primary key
#  about_type    :string           not null, indexed => [about_id]
#  level         :integer          default(1)
#  position      :integer
#  slug          :string
#  title         :string
#  created_at    :datetime         not null
#  updated_at    :datetime         not null
#  about_id      :uuid             not null, indexed => [about_type]
#  parent_id     :uuid             indexed
#  university_id :uuid             not null, indexed
#
# Indexes
#
#  index_communication_block_headings_on_about          (about_type,about_id)
#  index_communication_block_headings_on_parent_id      (parent_id)
#  index_communication_block_headings_on_university_id  (university_id)
#
# Foreign Keys
#
#  fk_rails_6d3de8388e  (parent_id => communication_block_headings.id)
#  fk_rails_ae82723550  (university_id => universities.id)
#
class Communication::Block::Heading < ApplicationRecord
  belongs_to  :university
  belongs_to  :about,
              polymorphic: true
  belongs_to  :parent, 
              class_name: 'Communication::Block::Heading',
              optional: true
  has_many    :children,
              class_name: 'Communication::Block::Heading',
              foreign_key: :parent_id
Arnaud Levy's avatar
Arnaud Levy committed
  has_many    :blocks,
              dependent: :nullify
Arnaud Levy's avatar
Arnaud Levy committed

  DEFAULT_LEVEL = 2
Arnaud Levy's avatar
Arnaud Levy committed
  
Arnaud Levy's avatar
Arnaud Levy committed
  scope :root, -> { where(level: DEFAULT_LEVEL) }
Arnaud Levy's avatar
Arnaud Levy committed
  scope :ordered, -> { order(:position) }
  default_scope { ordered }
Arnaud Levy's avatar
Arnaud Levy committed

Arnaud Levy's avatar
Arnaud Levy committed
  before_validation :compute_level

Arnaud Levy's avatar
Arnaud Levy committed
  def to_s
    "#{title}"
  end
Arnaud Levy's avatar
Arnaud Levy committed

  protected

  def compute_level
    self.level = parent ? parent.level + 1
                        : DEFAULT_LEVEL
  end
Arnaud Levy's avatar
Arnaud Levy committed
end