简体   繁体   中英

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. How can I get the vehicle_id inside the Event model?

You would normally use validates_uniqueness_of with a :scope, but the join association here won't work that way. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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