2010-05-26 57 views
0

好吧,我有一個通用的TimeSlot模型,它處理start_atend_at時間跨度。幾個模型來自這個,但我指的是在這個問題中的一個:AppointmentBlock這是Appointments的集合。我想驗證AppointmentBlock,以便在同一時間範圍內沒有其他AppointmentBlocks已經安排用於特定的Employee。由於AppointmentBlockTimeSlot多態關聯,你有AppointmentBlockstart_atend_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_atend_at我怎麼能與time_slots表讓這些條件下工作,加入?

回答

1

你可以用:加入參數上發現,與此類似:

blocks = AppointmentBlock.find(:first, 
      :conditions => ['employee_id = ? and (time_slots.start_at between ? and ? or time_slots.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], 
      :joins => 'join time_slots on time_slots.time_slot_role_id = appointment_blocks.id') 
+0

感謝威廉和歡迎計算器!我忘記了一些關於我的多態關係的重要信息(請參閱我編輯的帖子)。我認爲要做這項工作,我需要''在time_slots.time_slot_role_id = appointment_blocks.id'上加入time_slots' – DJTripleThreat 2010-05-26 19:27:56

+0

如果你用我剛剛評論過的部分編輯你的答案,我會接受你的答案。 – DJTripleThreat 2010-05-26 19:54:37

+0

更改了代碼以反映您的表格結構。很高興有幫助。 – William 2010-05-27 17:26:24