在rails上的ruby中使用连接表

假设我有两个数据库:一个用于学生,一个用于课程。 我希望能够为特定学生“添加”课程,并且能够将学生添加到特定课程。 我假设我需要在这里使用连接表,但我对如何使用它们有点迷失。 我最终希望能够做到这样的事情:

@class.students.find(@student_id) 

这会告诉我学生是否在课堂上。 我知道class级和学生之间的关系是’has_many’,反之亦然。 在迁移文件中做’t.references:students’是否能实现这一目标? 我尝试将该行添加到我的迁移文件中,然后尝试使用上面的语句查找内容并且它给了我一个错误。 我是RoR的新手,所以我甚至不确定实现这一目标的最佳方法是什么。 任何帮助表示赞赏!

是的,这是一个多对多的关系(class级有很多学生,学生有很多class级)。 为此你将使用has_many :through关系。 查看ActiveRecord::Associations的文档(Ctrl-F表示“关联连接模型”)。

在迁移中, t.references :students是如何指定belongs_to关系的,因为它只添加了student_id列(只能容纳一个id,即一个学生)。 但是,连接模型将包含两列: student_idclass_id 。 (顺便说一句,在Ruby中调用模型’Class’是在寻找麻烦。我可以建议’课程’吗?)

@Jordan所说的一切都是真的,这里采取的具体步骤:

  1. 创建迁移 : rails g model CourseStudent为n:m关系创建连接模型,并迁移到相应的表。
  2. 编辑迁移文件CreateCourseStudent ,使其包含以下内容:

     class CreateCourseStudent < ActiveRecord::Migration def change create_table :course_students do |t| # Your code comes here t.integer :student_id t.integer :course_id # Here comes the generated code t.timestamps end end end 
  3. 运行迁移: rake db:migrate 。 因此,连接表现在应该存在于您的数据库中。

  4. 将以下代码添加到模型中

     class Course < ActiveRecord::Base has_many :course_students has_many :students, :through => :course_students end class Student < ActiveRecord::Base has_many :course_students has_many :courses, :through => :course_students end class CourseStudent < ActiveRecord::Base belongs_to :student belongs_to :course end 

您现在可以使用方法belongs_tohas_many生成的方法:

  • @course.students
  • @student.courses

尝试在Rails指南中找到所有相关的事实和片段,在那里你应该找到你需要的所有信息。 祝好运!

这是一个老问题,但万一有人像我一样has_and_belongs_to_many这一点,你现在可以拥有关系has_and_belongs_to_many 。 所以是的,你会创建一个连接表:

 create_join_table :students, :courses do |t| t.integer :student_id t.integer :course_id end 

然后在模型中,你会说学生has_and_belongs_to_many :courses和课程has_and_belongs_to_many :students 。 没有必要创建名为CourseStudent的第三个类。 此链接包含所有这些信息