user.rb 1.35 KB
# frozen_string_literal: true

# == Schema Information
#
# Table name: users
#
#  id            :integer          not null, primary key
#  created_at    :datetime         not null
#  updated_at    :datetime         not null
#  deleted_at    :datetime
#  name          :string
#  mail          :string
#  password_hash :string
#  password_salt :string
#
class User < ApplicationRecord
  acts_as_paranoid
  has_paper_trail
  acts_as_heimdall

  attr_accessor :current_password

  validates :name, :mail, presence: true
  validates :password, presence: true, on: :create
  validates :password, confirmation: true

  before_save :encrypt_password

  has_many :bets, inverse_of: :user

  has_and_belongs_to_many :roles, inverse_of: :users,
                        class_name: 'HeimdallEngine::Role',
                        join_table: 'users_roles',
                        foreign_key: "user_id",
                        association_foreign_key: "role_id"

  accepts_nested_attributes_for :bets, reject_if: :all_blank,
    allow_destroy: false


  def user_score
    bets.active.sum :points
  end

  def encrypt_password
    return unless password.present?
    self.password_salt = BCrypt::Engine.generate_salt.force_encoding('UTF-8')
    self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
                                       .force_encoding('UTF-8')
  end
end