class User < ApplicationRecord rolify devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :access_periods, dependent: :destroy accepts_nested_attributes_for :access_periods, allow_destroy: true after_create :assign_default_role # Validation for date fields validate :end_date_after_start_date, if: -> { access_revoked && access_end_date.present? } # Override Devise method to consider access_revoked def active_for_authentication? super && !access_revoked end private def assign_default_role self.add_role(:user) unless self.has_any_role? end def end_date_after_start_date if access_start_date.present? errors.add(:access_end_date, 'must be provided when access is revoked') unless access_end_date.present? if access_end_date && access_end_date < access_start_date errors.add(:access_end_date, 'must be after the start date') end end end end