mirror of
https://github.com/ryankazokas/turbovault-app.git
synced 2026-04-16 23:22:53 +00:00
Moving to github
This commit is contained in:
47
app/models/collection.rb
Normal file
47
app/models/collection.rb
Normal file
@@ -0,0 +1,47 @@
|
||||
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
|
||||
Reference in New Issue
Block a user