Rails 3.如何在belongs_to关联中设置同一模型的两个实例?

时间:2012-07-11 19:05:29

标签: ruby-on-rails ruby associations

如果我有一个名为enrollments的表,这是我目前的基本注册设置:

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_id表格中添加guardian_2_idenrollments。我该如何设置?

1 个答案:

答案 0 :(得分:1)

您可能最好使用多态关联,例如:

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

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

对于每种情况是否有1,2或更多监护人而言,这个问题会给你一些灵活性。此外,您可以添加限制为2的验证。