在Rails中使用ruby连接表 [英] Using join tables in ruby on rails

查看:104
本文介绍了在Rails中使用ruby连接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有两个数据库:一个用于学生,一个用于课程.我希望能够将课程添加"到特定学生,也能够将学生添加到特定课程.我假设我需要在这里使用联接表,但是我对如何使用它们有些迷惑.我最终希望能够做类似的事情:

Lets say I have two databases: one for students and one for classes. I would like to be able to 'add' classes to a specific student and also be able to add students to a specific class. I assume I need to use a join table here but I am a little lost on how to use them. I would ultimately like to be able to do something like:

  @class.students.find(@student_id)

这会告诉我该学生是否在课堂上.我知道班级和学生之间的关系是"has_many",反之亦然.在迁移文件中执行't.references:students'可以做到吗?我尝试将该行添加到我的迁移文件中,然后尝试使用上述语句查找某些内容,这给了我一个错误.我是RoR的新手,所以我什至不确定实现此目标的最佳方法是什么.感谢您的帮助!

and this would tell me if the student is in the class or not. I know the relationship between classes and students is 'has_many' and vice versa. Does doing 't.references :students' in the migrate files accomplish that? I tried adding that line to my migrate file and then tried finding something using the statement above and it gave me an error. I am new to RoR so I am not even sure what the best way to go about achieving this is. Any help is appreciated!

推荐答案

是的,这是一个多对多的关系(班级有很多学生,学生有很多班级).为此,您将使用has_many :through关系.查看 ActiveRecord::Associations 的文档(按Ctrl-F 关联联接模型".

Yes, this is a many-to-many relationship (class has many students, student has many classes). For this you'll use a has_many :through relation. Take a look at the docs for ActiveRecord::Associations (Ctrl-F for "Association Join Models").

在迁移中,t.references :students是您指定belongs_to关系的方式,因为它仅添加了student_id列(该列只能容纳一个ID,即一个学生).但是,联接模型将具有两列:student_idclass_id. (顺便说一句,在Ruby中将模型称为类"正在引起麻烦.我建议使用课程"吗?)

In a migration, t.references :students is how you would specify a belongs_to relation, as it just adds a student_id column (which can only accommodate one id, i.e. one student). A join model, however, will have two columns: student_id and class_id. (Incidentally, calling a model 'Class' in Ruby is asking for trouble. Might I suggest 'Course'?)

这篇关于在Rails中使用ruby连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆