两个表之间的 Rails 双向关系

Rails both way relationship between two tables

提问人:Abenezer Daniel 提问时间:11/15/2023 更新时间:11/15/2023 访问量:75

问:

在Ruby on Rails中,我试图能够在两个表之间创建双向多对多关系。我想要路由和控制器之间的关系。例如,我希望能够执行以下两项操作:

teachers = school_class.teachers.all school_classes = teacher.school_classes.all因此,如果您能帮助我进行路由设置、控制器和此问题的模型,我将不胜感激。

我尝试使用has_and_belongs_to_many关联,我认为这是正确的方法,但我无法弄清楚其他任何事情。

Ruby-on-Rails Ruby-on-Rails-4 ActiveRecord

评论

0赞 zaphodbln_ 11/15/2023
因此,也许您想与我们分享您的模型,以便我们提供帮助

答:

1赞 tonystrawberry 11/15/2023 #1

当两个表之间存在关系时,它们之间必然需要一个关系表。many-to-many

relationship_table

因此,首先创建一个模型来创建您的关系表。

rails g model TeacherSchoolClass teacher:reference school_class:reference

然后在 你的 中添加行。models/teacher_school_class.rbbelongs_to

class TeacherSchoolClass < ApplicationRecord
  belongs_to :teacher
  belongs_to :school_class
end

最后,在 和 中,添加行。models/teacher.rbmodels/school_class.rbhas_many/through

class Teacher < ApplicationRecord
  has_many :teacher_school_classes, dependent: :destroy # Will destroy the related teacher_school_classes when teacher is destroyed
  has_many :school_classes, through: :teacher_school_classes # Will get all the school_classes for this teacher through the teacher_school_classes table
end

class SchoolClass < ApplicationRecord
  has_many :teacher_school_classes, dependent: :destroy # Will destroy the related teacher_school_classes when school_class is destroyed
  has_many :teachers, through: :teacher_school_classes # Will get all the teachers for this school_class through the teacher_school_classes table
end

然后,您将能够获得:

  • 特定教师的所有学校课程
  • 特定学校班级的所有教师
teacher.school_classes # Returns an ActiveRecord::Relation of SchoolClass
school_class.teachers # Returns an ActiveRecord::Relation of Teacher

参考: https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association