0

我有 3 个模型,一个有很多教师学生的学校。问题是学生可以属于学校教师,所以理论上他们总是通过关联属于学校。我将如何处理 Rails/Active Record 中的这种类型的数据结构?

    class School < AR::Base
      has_many :teachers
      has_many :students

    end

    class Teacher < AR::Base
      belongs_to :school
      has_many :students

    end

    class Student < AR::Base
      belongs_to ???

    end
4

2 回答 2

0

这个解决方案应该有效,但是您对您的介绍有疑问;你说“一个老师有很多学生”。这句话暗示“一个学生有一个老师”。

也许你应该设置一个 has_and_belongs_to_many 关联。

class School < AR::Base
  has_many :teachers
  has_many :students, :through => :teachers
end

class Teacher < AR::Base
  belongs_to :school
  has_many :students
end

class Student < AR::Base
  belongs_to :teacher
  belongs_to :school, :through => :teacher
end
于 2013-03-01T10:56:50.497 回答
0

显然你需要多态关联,可以这样做

class School < AR::Base
 has_many :teachers
 has_many :students, :as => :studentable
end

class Teacher < AR::Base
 belongs_to :school
 has_many :students
end

class Student < AR::Base
 belongs_to :studentable
end

不要忘记将 studentable_id 和 studentable_type 添加到学生模型中。

于 2013-03-01T12:55:02.330 回答