0
好吧,我有一個通用的TimeSlot
模型,它處理start_at
和end_at
時間跨度。幾個模型來自這個,但我指的是在這個問題中的一個:AppointmentBlock
這是Appointments
的集合。我想驗證AppointmentBlock
,以便在同一時間範圍內沒有其他AppointmentBlocks
已經安排用於特定的Employee
。由於AppointmentBlock
有TimeSlot
多態關聯,你有AppointmentBlock
的start_at
和end_at
通過訪問TimeSlot
像這樣:appt_block.time_slot.start_at
這意味着,我需要有某種在我:conditions
加入我的find()
方法調用。這是我到目前爲止的代碼:Rails:使用find方法訪問多態關係連接表
#inside my time_slot.rb model
belongs_to :time_slot_role, :polymorphic => true
#inside my appointment_block.rb model
has_one :time_slot, :as => :time_slot_role, :dependent => :destroy
validate :employee_not_double_booked
def employee_not_double_booked
unless self.employee_id
# this find's condition is incorrect because I need to join time_slots to get access
# to start_at and end_at. How can I do this?
blocks = AppointmentBlock.find(:first,
:conditions => ['employee_id = ? and (start_at between ? and ? or end_at between ? and ?)',
self.employee_id, self.time_slot.start_at, self.time_slot.end_at,
self.time_slot.start_at, self.time_slot.end_at])
# pseudo code:
# collect a list of appointment blocks that end after this
# apointment block starts or start before this appointment
# block ends that are also associated with this appointment
# blocks assigned employee
# if the count is great then 0 the employee has been double
# booked.
# if a block was found that means this employee is getting
# double booked so raise an error
errors.add "AppointmentBlock",
"has already been scheduled during this time" if blocks
end
end
由於AppointmentBlock
沒有一個start_at
或end_at
我怎麼能與time_slots
表讓這些條件下工作,加入?
感謝威廉和歡迎計算器!我忘記了一些關於我的多態關係的重要信息(請參閱我編輯的帖子)。我認爲要做這項工作,我需要''在time_slots.time_slot_role_id = appointment_blocks.id'上加入time_slots' – DJTripleThreat 2010-05-26 19:27:56
如果你用我剛剛評論過的部分編輯你的答案,我會接受你的答案。 – DJTripleThreat 2010-05-26 19:54:37
更改了代碼以反映您的表格結構。很高興有幫助。 – William 2010-05-27 17:26:24