mirror of
https://github.com/ryankazokas/turbovault-app.git
synced 2026-04-16 21:02:52 +00:00
57 lines
1.3 KiB
Ruby
57 lines
1.3 KiB
Ruby
# typed: true
|
|
|
|
class Collection < ApplicationRecord
|
|
extend T::Sig
|
|
# 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
|
|
sig { returns(Integer) }
|
|
def game_count
|
|
games.count
|
|
end
|
|
|
|
sig { returns(Integer) }
|
|
def total_game_count
|
|
game_count + subcollections.sum(&:total_game_count)
|
|
end
|
|
|
|
sig { returns(T::Boolean) }
|
|
def root?
|
|
parent_collection_id.nil?
|
|
end
|
|
|
|
sig { returns(T::Boolean) }
|
|
def subcollection?
|
|
parent_collection_id.present?
|
|
end
|
|
|
|
private
|
|
|
|
sig { void }
|
|
def cannot_be_own_parent
|
|
if parent_collection_id.present? && parent_collection_id == id
|
|
errors.add(:parent_collection_id, "cannot be itself")
|
|
end
|
|
end
|
|
|
|
sig { void }
|
|
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
|