2012-07-11 102 views
0

如果我有一個名爲enrollments表,這是我目前的基本入學設置:Rails 3.如何在belongs_to關聯中設置相同模型的兩個實例?

class Enrollment < ActiveRecord::Base  
    belongs_to :father 
    belongs_to :mother 
    belongs_to :child 
end 

class Father < ActiveRecord::Base 
    has_many :enrollments 
    has_many :children 
    validates :first_name, :presence => true 
    validates :last_name, :presence => true 
end 

現在我想一個guardian_1_idguardian_2_id添加到enrollments表。我將如何設置?

回答

1

您可能最好使用多態關聯,例如,

class Enrollment 
    belongs_to :enrollable, :polymorphic => true 
end 

class Father 
has_many :enrollments, :as => enrollable 
end 

在每個情況下是否存在1,2個或更多監護人的問題上,這個小組給你一些靈活性。另外,你可以添加兩次驗證。

相關問題