[英]Get attribute of polymorphic parent before save, in Rails 3?
我有车辆,每个车辆可以有很多预订。 每个预订可以有许多事件。 当我针对现有车辆验证新的预订和事件时,出现了这个问题。
在验证事件模型时,我需要遍历车辆并找到所有预订以及任何可能与新预订发生冲突的事件,然后再实际保存新的预订和事件。
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
创建预订时,它具有vehicle_id。 如何在事件模型中获取vehicle_id?
通常,您可以通过带有:scope的validates_uniqueness_of来使用,但是这里的联接关联不能那样工作。 这是一个自定义唯一性验证器的示例:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.