2013-04-17 158 views
0

我想補充另一列到模型關聯 看到例如 現在我有一個新的列還需要檢查Ruby on Rails的協會

醫生

id 
name 
organization_id (new one) 

約會

id 
physician_id 
patient_id 
organization_id (new one) 
appointment_date 

患者

id 
name 
organization_id (new one) 

我的要求是,如果有三個表有不同的organization_ID,足協不應該工作。

在控制器

,我是使用代碼: @all_patients = Physician.find_by_id_and_organization_id(PARAMS [:編號],則params [:ORGID])。患者

讓所有的患者都屬於醫生和他們展示UI。 如果一些髒數據,表約會和患者可能有不正確的organization_id。我想要的是,UI不應該顯示數據organization_id不是預期的。 例如,我有在DB數據表示:

醫師:
1 「醫師1」,1
2中, 「醫師2」,1個

約會
1,1,1 ,1,2013-1-1
2,1,2,1,2013-1-1
3,1,3,1,2013-1-1
4,1,4,2,2013- 1-1

患者
1, 「患者1」,1
2, 「患者2」,2
3中, 「患者3」,1
3, 「患者4」,1

如果我使用Physician.find_by_id_and_organization_id(1,1)。患者,我希望得到以下患者
1,「患者1」,1
但現在我不知道該如何配置模型關係,我得到了整個病人的數據。

那麼,如何配置模型?

回答

0

appointments中不需要額外的列。 在約會模式,你可以只是做一個額外的校驗回調,並確保病人和醫生都屬於同一個組織:

class Appointment < ActiveRecord::Base 
    validate :have_to_be_in_the_same_organization 

    def have_to_be_in_the_same_organization 
     unless Patient.find(patient_id).organization_id == Physician.find(physician_id).organization_id 
      errors.add(:base, "The physician and the patient must be in the same organization to create an appointment!") 
     end 
    end 
end 

解決方案2:

如果你不希望它使任何錯誤,而要將其重定向到某個地方,但不嘗試創建一個約會,你可以在你的create行動在appointmentscontrollerbefore filter

class AppointmentsController < ActiveRecord::Base 
before_filter :have_to_be_in_the_same_organization, :only => [:create] 

    def have_to_be_in_the_same_organization 
       unless Patient.find(params[:patient_id]).organization_id == Physician.find(params[:physician_id]).organization_id 
        redirect_to somewhere_path 
       end 
    end 
end 
+0

此驗證來了一封RROR。我不希望它提示錯誤。我希望它沒有任何回報。就像沒有找到數據一樣。再次感謝。 – Morris

+0

你想將它重定向到某個地方嗎?使問題更清楚。顯示'約會控制器'的'create'動作 – Zippie

+0

我在控制器中更新了我的回答 – Zippie