我有两个模型Appointment和Schedule,在Appointment中我有一个名为date的时间字段,在Schedule中我有start_time和end end_time字段。
我想将date中的值与start_time和end_time中的值进行比较,看看是否有可能在那个时间进行约会。
如何比较这些值?
create_table "appointments", :force => true do |t|
t.integer "doctor_id"
t.date "adate"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.time "atime"
end
create_table "schedules", :force => true do |t|
t.string "day"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "doctor_id"
t.time "start_time"
t.time "end_time"
end
它应该是一个验证,但我应该实现这个吗?
模型class Appointment < ActiveRecord::Base
attr_accessible :adate, :atime, :doctor_id
validates :adate, :presence => true
belongs_to :doctor
validates_date :adate, :after => lambda { Date.current }
end
class Schedule < ActiveRecord::Base
attr_accessible :doctor_id, :day, :end_time, :start_time
belongs_to :doctor
end
从http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-methods可以看到如何编写任意的验证方法。
在你的情况下,你可能会写这种形式的东西。
class Appointment < ActiveRecord::Base
# ... All the other stuff
validate :appointment_time_is_valid_for_day
def appointment_time_is_valid_for_day
# TODO: Get the schedule for that day/doctor.
unless schedule.start_time <= atime and
atime <= schedule.end_time
errors.add(:atime, "Doctor's not in at this time")
end
end
end
假设您已经有某种方法可以在预约当天获得医生的时间表。我不太了解你们的模型,没法告诉你们怎么做。