在Rails 3.1中处理时间段 [英] Dealing with time periods in Rails 3.1
问题描述
我正在开发Rails 3.1中的预订系统.我已经为预订创建了一个模型:
I'm developing a booking system in Rails 3.1. I have created a model for a Booking:
# == 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字段,还必须对其进行验证.
So what I want to do is to validate each entry and check whether the desired time period (booked_from - booked_to) is overlapping any period of another booking with the same product_id. The products also have an available_from and available_to field which it also has to validate against.
我该怎么做?
推荐答案
检查是否可行:
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
它只是检查是否有任何现有记录的booked_from和booked__满足以下条件之一(假设您的新预订时间为16:00至17:00):
It just checks if there is any existing records whose booked_from and booked_to satisfy one of the following conditions (suppose your new booking is from 16:00 to 17:00):
- 开始于新预订之前,但尚未结束(例如15:00-16:30或15:00-17:30)
- 它在新的预订期限内开始(例如16:20-16:50或16:30-17:30)
这篇关于在Rails 3.1中处理时间段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!