Files
turbovault-app/app/models/game.rb
2026-03-28 19:24:29 -04:00

67 lines
2.3 KiB
Ruby

class Game < ApplicationRecord
# Associations
belongs_to :user
belongs_to :platform
has_many :game_genres, dependent: :destroy
has_many :genres, through: :game_genres
has_many :collection_games, dependent: :destroy
has_many :collections, through: :collection_games
has_many :igdb_match_suggestions, dependent: :destroy
belongs_to :igdb_game, foreign_key: :igdb_id, primary_key: :igdb_id, optional: true
# Enums
enum :format, { physical: "physical", digital: "digital" }
enum :completion_status, {
backlog: "backlog",
currently_playing: "currently_playing",
completed: "completed",
on_hold: "on_hold",
not_playing: "not_playing"
}, prefix: true
enum :condition, {
cib: "cib", # Complete in Box
loose: "loose",
sealed: "sealed",
good: "good",
fair: "fair"
}, prefix: true
# Validations
validates :title, presence: true
validates :format, presence: true
validates :date_added, presence: true
validates :user_rating, inclusion: { in: 1..5, message: "must be between 1 and 5" }, allow_nil: true
validates :condition, presence: true, if: :physical?
validates :digital_store, presence: true, if: :digital?
# Callbacks
before_validation :set_date_added, on: :create
# Scopes
scope :physical_games, -> { where(format: "physical") }
scope :digital_games, -> { where(format: "digital") }
scope :currently_playing, -> { where(completion_status: "currently_playing") }
scope :completed, -> { where(completion_status: "completed") }
scope :backlog, -> { where(completion_status: "backlog") }
scope :by_platform, ->(platform_id) { where(platform_id: platform_id) }
scope :by_genre, ->(genre_id) { joins(:genres).where(genres: { id: genre_id }) }
scope :recent, -> { order(date_added: :desc) }
scope :alphabetical, -> { order(:title) }
scope :rated, -> { where.not(user_rating: nil).order(user_rating: :desc) }
scope :igdb_matched, -> { where.not(igdb_id: nil) }
scope :igdb_unmatched, -> { where(igdb_id: nil) }
scope :needs_igdb_review, -> { joins(:igdb_match_suggestions).where(igdb_match_suggestions: { status: "pending" }).distinct }
# Class methods
def self.search(query)
where("title ILIKE ?", "%#{sanitize_sql_like(query)}%")
end
private
def set_date_added
self.date_added ||= Date.current
end
end