我正在开发Rails 3.1中的预订系统。我为预订创建了一个模型:
# == Schema Information
#
# Table name: bookings
#
# id :integer not null, primary key
# product_id :integer
# customer_id :integer
# booked_from :datetime
# booked_to :datetime
# paid :boolean
# payment_type :string(255)
# created_at :datetime
# updated_at :datetime
#
所以我想要做的是验证每个条目并检查所需的时间段(booked_from - booked_to)是否与具有相同product_id的另一个预订的任何时段重叠。这些产品还有一个available_from和available_to字段,它也必须进行验证。
我该怎么做?
答案 0 :(得分:3)
检查是否有效:
class Booking
validate :booking_period_not_overlapped
private
def booking_period_not_overlapped
unless Booking.where(
'(booked_from <= ? AND booked_to >= ?) OR (booked_from >= ? AND booked_from <= ?)',
booked_from, booked_from,
booked_from, booked_to
).empty?
errors.add(:booked_from, 'Invalid period.')
end
end
end
它只检查是否有任何现有记录,其expected_from和booked_to满足以下条件之一(假设您的新预订时间为16:00至17:00):