我有两个模型约会和时间表,在预约中我有一个名为adate的时间字段,在计划中我有start_time和end end_time字段。
我想将adate中的值与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
答案 0 :(得分:1)
从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
这假设您已经有一些方法可以在预约当天获得医生的时间表。我对你的模型不太了解,告诉你如何做到这一点。