class Collection < ApplicationRecord # Associations belongs_to :user belongs_to :parent_collection, class_name: "Collection", optional: true has_many :subcollections, class_name: "Collection", foreign_key: "parent_collection_id", dependent: :destroy has_many :collection_games, dependent: :destroy has_many :games, through: :collection_games # Validations validates :name, presence: true validate :cannot_be_own_parent validate :subcollection_depth_limit # Scopes scope :root_collections, -> { where(parent_collection_id: nil) } # Instance methods def game_count games.count end def total_game_count game_count + subcollections.sum(&:total_game_count) end def root? parent_collection_id.nil? end def subcollection? parent_collection_id.present? end private def cannot_be_own_parent if parent_collection_id.present? && parent_collection_id == id errors.add(:parent_collection_id, "cannot be itself") end end def subcollection_depth_limit if parent_collection.present? && parent_collection.parent_collection.present? errors.add(:parent_collection_id, "cannot nest more than one level deep") end end end