我如何将学生与Rails课程联系起来

问题描述 投票:0回答:2

我的学生和课程都在我的红宝石模型和控制器中,所以我想将这两件事联系起来,向用户和他注册的课程显示,然后单击这些课程以查看该课程的内容。我是红宝石的新手,所以我对has_many不太了解,我找不到能使我想要工作的东西

我已经使用脚手架来创建模型和控制器,用户只有一个名字,电子邮件和课程都只有course_name

学生:

 create_table :student do |t|
      t.string :name
      t.string :email

课程:

create_table :cursos do |t|
  t.string :name

  t.timestamps

在学生索引中,我只列出我拥有的所有学生。halp pls

ruby-on-rails ruby ruby-on-rails-5
2个回答
0
投票

好像您想在studentscourses之间使用多对多关联。有多种方法可以实现此目的。我将使用has_many :though中描述的here选项,在其中添加一个名为StudentCourse的附加模型。

因此,在您的情况下,您将:

  1. 使用rails generate model StudentCourse student:references model:references生成此StudenCourse模型

  2. 将以下内容添加到Student模型中

    class Student
      ...
      has_many :student_courses
      has_many :courses, through: student_courses
      ...
    end
  1. 将以下内容添加到Course模型中
    class Course
      ...
      has_many :student_courses
      has_many :students, through: student_courses
      ...
    end
  1. 使用rake db:migrate运行迁移
  2. 现在您可以开始将学生添加到课程中,反之亦然。例如:
    Student.last.courses << Course.last
    Course.first.students << Student.first

并且在您的控制器中,您只需调用student.courses即可查看与给定学生相关的课程,或单击course.students即可查看参加特定课程的学生。

注意CourseStudent模型现在如何使用has_many: ..., through: :student_courses相互关联。这个新模型允许通过我们创建的联接表进行多对多关联。使用这种多对多关联的另一个好处是灵活性。例如,您可能要开始记录学生是否已放弃特定课程。您只需将dropped_at列添加到此新student_courses表中即可。


-1
投票

您需要在模型类中设置关系,即关联。

现在您可能在名为app / models的文件夹中有两个模型类(假设脚手架已创建它们):

  • app / models / student.rb
  • app / models / curso.rb

在app / models / student.rb中,您需要具有以下内容:

class Student < ActiveRecord::Base

  belongs_to :curso

end

在app / models / curso.rb中,您需要具有以下内容:

class Curso < ActiveRecord::Base

  has_many :students

end

这就是在Rails中创建关联的方式。

© www.soinside.com 2019 - 2024. All rights reserved.