我的学生和课程都在我的红宝石模型和控制器中,所以我想将这两件事联系起来,向用户和他注册的课程显示,然后单击这些课程以查看该课程的内容。我是红宝石的新手,所以我对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
好像您想在students
和courses
之间使用多对多关联。有多种方法可以实现此目的。我将使用has_many :though
中描述的here选项,在其中添加一个名为StudentCourse
的附加模型。
因此,在您的情况下,您将:
使用rails generate model StudentCourse student:references model:references
生成此StudenCourse模型
将以下内容添加到Student
模型中
class Student
...
has_many :student_courses
has_many :courses, through: student_courses
...
end
Course
模型中 class Course
...
has_many :student_courses
has_many :students, through: student_courses
...
end
rake db:migrate
运行迁移 Student.last.courses << Course.last
Course.first.students << Student.first
并且在您的控制器中,您只需调用student.courses
即可查看与给定学生相关的课程,或单击course.students
即可查看参加特定课程的学生。
注意Course
和Student
模型现在如何使用has_many: ..., through: :student_courses
相互关联。这个新模型允许通过我们创建的联接表进行多对多关联。使用这种多对多关联的另一个好处是灵活性。例如,您可能要开始记录学生是否已放弃特定课程。您只需将dropped_at
列添加到此新student_courses
表中即可。
您需要在模型类中设置关系,即关联。
现在您可能在名为app / models的文件夹中有两个模型类(假设脚手架已创建它们):
在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中创建关联的方式。