class Board < ApplicationRecord
  belongs_to :course, touch: true

  has_many :messages, -> { order(created_on: :desc) }, dependent: :destroy
  has_many :visible_messages, -> { visible }, class_name: "Message"
  belongs_to :last_message, class_name: 'Message', foreign_key: :last_message_id, optional: true

  scope :roots, -> { where(parent_id: 0)}

  validates :name, presence: true, length: {maximum: 30}
  # validates :description, presence: true, length: {maximum: 255}

  # 子讨论区
  def children
    Board.where(parent_id: self.id).reorder("position asc")
  end

  def fix_name
    return name if parent_id != 0

    course_modules = self.course.board_course_modules
    course_modules.present? ? course_modules[0].module_name : self.name
  end

end
