class User < ApplicationRecord has_secure_password validations: false has_many :sessions, dependent: :destroy has_many :matches_as_player1, class_name: "Match", foreign_key: :player1_id, dependent: :restrict_with_exception, inverse_of: :player1 has_many :matches_as_player2, class_name: "Match", foreign_key: :player2_id, dependent: :restrict_with_exception, inverse_of: :player2 has_many :match_players, foreign_key: :player_id, dependent: :destroy, inverse_of: :player has_many :matches, through: :match_players, source: :match has_one_attached :avatar normalizes :nickname, with: ->(n) { n.strip } validates :nickname, presence: true, uniqueness: { case_sensitive: false }, length: { minimum: 3, maximum: 24 } validates :rating, presence: true validates :password, presence: true, length: { minimum: 6 }, if: -> { new_record? || password_digest_changed? } validate :avatar_content_type, if: -> { avatar.attached? } # All matches of this user that have finished, newest first. def finished_matches Match.where("player1_id = :id OR player2_id = :id", id: id) .where.not(finished_at: nil) .order(finished_at: :desc) end def avatar_url return nil unless avatar.attached? options = Rails.application.routes.default_url_options.presence || { host: "localhost", port: 3000 } Rails.application.routes.url_helpers.rails_blob_url(avatar, options) end private def avatar_content_type unless avatar.blob.content_type.in?(%w[image/png image/jpeg image/gif image/webp]) errors.add(:avatar, "must be a PNG, JPEG, GIF or WebP image") end end end