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

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

问题描述

假设我有两个数据库:一个用于学生,一个用于班级.我希望能够为特定学生添加"课程,也能够将学生添加到特定课程.我假设我需要在这里使用连接表,但我对如何使用它们有点迷茫.我最终希望能够执行以下操作:

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<的文档/a>(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 中调用模型Class"是自找麻烦.我可以建议使用Course"吗?)

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'?)

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

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