class MaintenanceEntry < ApplicationRecord belongs_to :vehicle belongs_to :updated_by_user, class_name: "User" validates :name, :notes, :date, presence: true validates :odometer, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } validates :cost, presence: true, numericality: { greater_than_or_equal_to: 0 } validate :date_cannot_be_in_the_future validate :name_matches_vehicle_schedule private def date_cannot_be_in_the_future return if date.blank? || date <= Date.current errors.add(:date, "can't be in the future") end def name_matches_vehicle_schedule return if vehicle.blank? || name.blank? scheduled = vehicle.maintenance_schedules.any? do |schedule| schedule.active? && schedule.maintenance_type.casecmp?(name) end scheduled ||= vehicle.maintenance_schedules.active.where("lower(maintenance_type) = ?", name.downcase).exists? if vehicle.persisted? return if scheduled errors.add(:name, "must match a maintenance schedule for the vehicle") end end