2012-04-17 21 views
0

我正在建立一個課程申請系統。高中,本科和研究生都可以申請這門課程。他們必須填寫一些申請表格。Rails:處理幾個相似的模型類?

但是,他們的信息形式是相似的,但不完全一樣。每個學生都有姓名,電話號碼,電子郵件,地址等,但只有本科生必須提供他們的GPA,並且研究生必須告訴他們正在研究哪個實驗室。還有其他的細微差別...

那麼我該如何處理呢?製作一張大桌子,但是讓高中生的'GPA'專欄留空?或者使用三個單獨的表?

此外,存在Student之間的一些關係(或者,在三個表的情況下,HighSchoolStudentUndergraduateStudentGraduateStudent)等模式。例如,Course有很多Student s,Student有很多Question s等等。

回答

1

您可以使用組合STIStore功能來實現此功能。

聲明Student的基本模型,其文本列名爲settings

class Student < ActiveRecord::Base 
    store :settings 
    # name, email, phone, address etc.. 
end 


class HighSchoolStudent < Student 
    # declare HighSchoolStudent specific attributes 
    store_accessor :settings, :gpa 
end 


class UndergraduateStudent < Student 
    # declare UndergraduateStudent specific attributes 
    store_accessor :settings, :attr1 
end 

class GraduateStudent< Student 
    # declare GraduateStudent specific attributes 
    store_accessor :settings, :attr2 
end 

在上面的示例中,HighSchoolStudent實例將具有稱爲gpa的屬性。

0

您可以使用您想要的離開GPA爲空的選項,併爲該模型設置自定義驗證,以便僅根據學生類型進行檢查。單表繼承也是一種選擇,您可以在數據庫表的列中指定不同的類名稱,然後只需將這些類添加到模型目錄中。你可以在這裏看到一些文檔:http://api.rubyonrails.org/classes/ActiveRecord/Base.html

我以前沒有試過STI,但是考慮到你上面提到的內容,我可能會選擇那條路線,從我的代碼分支出去,看看它是如何氾濫的。

相關問題