Reputation: 1301
I have two models Appointment and Schedule, in Appointment I have a time field called adate and in schedule I have start_time and end end_time fields.
I want to compare the value in adate with the the values within start_time and end_time to see if is possible to make the appointment at that hour.
How can I compare those values?
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
It should be a validation but should I implement this?
Model
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
Upvotes: 0
Views: 73
Reputation: 3468
From http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-methods, you can see how to write arbitrary methods for validation.
In your case, you would probably write something of this form.
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
This assumes that you already have some way to get the schedule of the doctor on the day of the appointment. I don't know enough about your models to tell you how to do this.
Upvotes: 1