Le voci si possono modificare o eliminare se registrate per errore, e la ricerca non va più in errore SQL sul campo email. Co-authored-by: Cursor <cursoragent@cursor.com>
42 lines
1.3 KiB
Ruby
42 lines
1.3 KiB
Ruby
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(
|
|
"contacts.first_name ILIKE :q OR contacts.last_name ILIKE :q OR contacts.email ILIKE :q OR contacts.phone ILIKE :q OR contacts.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
|