简体   繁体   English

使用 Rails 4 从多对多关系中获取数据

[英]Getting data from many to many relation with rails 4

I am developing a rails app with mysql database.我正在开发一个带有 mysql 数据库的 rails 应用程序。

Theres bunch of tables but for this task I am using only 3. Students, Courses and CoursesPerStudent.有一堆表格,但对于这个任务,我只使用了 3 个。Students、Courss 和 CoursesPerStudent。

I have models for students and courses(no model for the third).我有学生和课程的模型(第三个没有模型)。 The tables are already populated.表已经填充。

The tables:表:

students - id,name,family,address,phone,email,status,path学生 - 身份证、姓名、家庭、地址、电话、电子邮件、状态、路径
courses - courseCode, courseName, hours课程 - 课程代码、课程名称、学时
coursesperstudent - code, student(same ids as in students table ids but not a oreign key),path,course(courses table code(foreign key)),examMark. courseperstudent - 代码、学生(与学生表 ID 中的 ID 相同但不是外键)、路径、课程(课程表代码(外键))、考试标记。

Now the thing is i need to show for each student a list of the courses realted to him.现在的事情是我需要为每个学生展示一份与他相关的课程清单。

How should i do it?我该怎么做? Should i create model for the third table?我应该为第三个表创建模型吗? how should i call it?我应该怎么称呼它? and combine the two other tables in one to show specific courses?并将其他两个表合二为一以显示特定课程?

Or there some other way?还是有其他办法?

Hopefully someone will help because im out of answers.希望有人会帮忙,因为我没有答案。

If you make right has_and_belongs_to_many association you can call:如果你做出正确的 has_and_belongs_to_many 关联,你可以调用:

Student.find(id).courses  

it return collection of courses它返回课程集合

http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM