简体   繁体   English

在Rails 3中保存之前获取多态父级的属性吗?

[英]Get attribute of polymorphic parent before save, in Rails 3?

I have Vehicles, each can have many bookings. 我有车辆,每个车辆可以有很多预订。 Each Booking can have many Events. 每个预订可以有许多事件。 This question comes as I validate a new Booking and Event against an existing Vehicle. 当我针对现有车辆验证新的预订和事件时,出现了这个问题。

When validating the Event model I need to traverse up to the Vehicle and find all the Bookings and any Events that may clash with the new one, before I've actually saved the new Booking and 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

When creating the Booking it has vehicle_id. 创建预订时,它具有vehicle_id。 How can I get the vehicle_id inside the Event model? 如何在事件模型中获取vehicle_id?

You would normally use validates_uniqueness_of with a :scope, but the join association here won't work that way. 通常,您可以通过带有:scope的validates_uniqueness_of来使用,但是这里的联接关联不能那样工作。 Here's an example of a custom uniqueness validator: 这是一个自定义唯一性验证器的示例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM