class Contact < ApplicationRecord include Auditable belongs_to :organization has_many :activities, dependent: :nullify has_many :tasks, dependent: :nullify has_many :mailing_recipients, dependent: :nullify validates :first_name, :last_name, presence: true validates :preferred_contact_method, inclusion: { in: Catalog::CONTACT_METHODS.keys }, allow_blank: true validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_blank: true before_save :ensure_single_primary, if: -> { primary_contact? && organization_id.present? } scope :primary_first, -> { order(primary_contact: :desc, last_name: :asc, first_name: :asc) } scope :search, ->(query) { return all if query.blank? q = "%#{sanitize_sql_like(query.strip)}%" where( "first_name ILIKE :q OR last_name ILIKE :q OR email ILIKE :q OR phone ILIKE :q OR mobile ILIKE :q", q: q ) } def full_name "#{first_name} #{last_name}" end def preferred_contact_method_label Catalog.label_for(Catalog::CONTACT_METHODS, preferred_contact_method) end private def ensure_single_primary scope = organization.contacts scope = scope.where.not(id: id) if persisted? scope.update_all(primary_contact: false) end end