0

我有车辆,每个可以有很多预订。每个预订可以有许多事件。当我针对现有车辆验证新的预订和活动时,就会出现这个问题。

在验证 Event 模型时,我需要遍历 Vehicle 并找到所有 Bookings 和任何可能与新的 Bookings 冲突的 Event,然后才实际保存新的 Bookings 和 Event。

Class Event < ActiveRecord::Base
  belongs_to :eventable, :polymorphic => true
end

Class Booking < ActiveRecord::Base
  belongs_to :vehicle
  has_many :events, :as => :eventable
end

Class Vehicle < ActiveRecord::Base
  has_many :bookings
end

创建预订时,它具有车辆 ID。如何在 Event 模型中获取 vehicle_id?

4

1 回答 1

1

您通常会将 validates_uniqueness_of 与 :scope 一起使用,但此处的连接关联不会那样工作。这是自定义唯一性验证器的示例:

class Booking
  # Create a custom validation
  validate :verify_unique_vehicle_date

private
  def verify_unique_vehicle_date
    if booking = Booking.includes(:events).where('vehicle_id = ? AND events.date IN (?)', self.vehicle_id, self.events.map(&:date)).first
      errors.add(:vehicle, "already booked on #{booking.events.map(&:date).join(',')}")
    end
  end
end
于 2012-09-20T19:31:05.473 回答