问题描述
尝试验证"对象日期唯一性的最佳方法是什么.
What would be the best approach to trying to "validate" uniqueness of dates for object.
-
例如,我有一个房间,一次只能有一个人.
So for example, I have a Room, that can only have 1 person in it at a time.
用户可以提前预订此房间.
A User can book this Room in advance.
当前的房间预订时间为3月1日至3月5日.
Currently the Room is booked from the 1st of March to the 5th of March.
我想阻止任何人在那些日期再次预订.
I want to prevent anyone from booking again on those dates.
因此,如果有人尝试从2月25日到3月2日预订房间,我需要告诉他们他们不能,因为房间已被预订满.
So if someone attempts to book a room from the 25th of Feb to the 2nd of March, I need to tell them they cannot, because the room is fully booked.
-
我正在使用Rails 3.0
I am using Rails 3.0
推荐答案
我刚刚编写了一个简单的应用程序来进行测试.这就是我最终在模型验证中使用的东西.
I just wrote a simple app to test this out. Here's what I ended up using in the model validation.
class Booking < ActiveRecord::Base
validate :uniqueness_of_date_range
private
def uniqueness_of_date_range
errors.add(:start_date, "is not available") unless Room.where("? >= start_date AND ? <= end_date",
start_date, start_date).count == 0
errors.add(:end_date, "is not available") unless Room.where("? >= start_date AND ? <= end_date",
end_date, end_date).count == 0
end
end
第一个自定义验证将检查当前记录的start_date是否在任何记录的start_date和end_date之间,而第二个则对end_date执行相同的操作.您可能想要显示更好的错误消息(例如,通过执行类似的查询(使用.all而不是.count并添加所有配对室的详细信息.)
The first custom validation checks to see if the current record's start_date falls between the start_date and end_date of any record, and second one does the same for end_date. You might want to show a better error message (like what is the start/end date of the record(s) that is/are clashing with the current one by doing a similar query (using .all instead of .count, and adding all the details of matching rooms).
这是我使用的数据库迁移
Here's the db migration I used
class CreateBookings < ActiveRecord::Migration
def self.up
create_table :bookings do |t|
t.date :start_date
t.date :end_date
t.string :title
t.timestamps
end
end
def self.down
drop_table :bookings
end
end
这篇关于带有验证的预订类型系统-Rails 3.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!