Added customer composite key
This commit is contained in:
@@ -1,7 +1,40 @@
|
||||
class Customer < ApplicationRecord
|
||||
# Use Rails 7.1's native composite primary key
|
||||
self.primary_key = %i[first_name surname original_phone]
|
||||
|
||||
belongs_to :company
|
||||
|
||||
validates :name, presence: true, uniqueness: { scope: :company_id }
|
||||
validates :first_name, presence: true
|
||||
validates :surname, presence: true
|
||||
validates :phone, presence: true
|
||||
validates :original_phone, presence: true
|
||||
validates :company_id, presence: true
|
||||
|
||||
validates :first_name, uniqueness: {
|
||||
scope: %i[surname original_phone company_id],
|
||||
message: -> { I18n.t('customers.customer.already_exists') }
|
||||
}
|
||||
|
||||
validates :birthyear, numericality: {
|
||||
only_integer: true,
|
||||
greater_than: 1900,
|
||||
less_than_or_equal_to: -> { Time.current.year }
|
||||
}, allow_nil: true
|
||||
|
||||
before_validation :set_original_phone, on: :create
|
||||
|
||||
def full_name
|
||||
[first_name, surname].compact_blank.join(' ')
|
||||
end
|
||||
|
||||
# Add method for URL generation
|
||||
def to_param
|
||||
[first_name, surname, original_phone].join('_')
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_original_phone
|
||||
self.original_phone = phone if original_phone.blank?
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
class Reservation < ApplicationRecord
|
||||
belongs_to :company
|
||||
belongs_to :customer
|
||||
belongs_to :customer,
|
||||
primary_key: %i[first_name surname original_phone],
|
||||
query_constraints: %i[customer_first_name customer_surname customer_original_phone]
|
||||
belongs_to :team
|
||||
|
||||
validates :company_id, presence: true
|
||||
validates :customer_id, presence: true
|
||||
validates :team_id, presence: true
|
||||
|
||||
# Remove customer_id validation since we're using composite key
|
||||
validates :customer_first_name, :customer_surname, :customer_original_phone, presence: true
|
||||
|
||||
# Add validation to ensure customer exists
|
||||
validate :customer_must_exist
|
||||
|
||||
private
|
||||
|
||||
def customer_must_exist
|
||||
unless Customer.exists?(first_name: customer_first_name,
|
||||
surname: customer_surname,
|
||||
original_phone: customer_original_phone)
|
||||
errors.add(:base, "Selected customer does not exist")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class ReservationSerializer < ActiveModel::Serializer
|
||||
|
||||
Reference in New Issue
Block a user