新手问题 模型之间的多对多关联 controller 和 model 应该怎么命名

lyb124553153 · May 03, 2017 · Last by baurine replied at May 03, 2017 · 1710 hits

比如 students : teachers = n : n 是多对多关联 我已经生成了一个 students_teahcers 表,表中有两列 student_id 和 teacher_id

1.模型的话应该要怎么命名 是 StudentsTeahcers,还是 StudentTeacher 2.传 student_id 查与之对应的 teacher 的时候, 2 在 student 和 teacher 之间创建关联,以及。update 方法应该怎么写

应该是 has_and_belongs_to_many 时不需要关联表模型、需要关联表模型时用 has_many through、查询和更新可以参考 activerecord associations

按单词的首字母顺序来排先后,应该命名为 StudentsTeahcers,多对多,所以都用复数

3 Floor has deleted

你这明显答非所问啊,多对多跟多态根本不是一回事!

如果是我,我会将这个表名命名为 student_teacher_relationships (复数), 把 model 命名为 StudentTeacherRelationship (单数),或者表名简化为 relationships (复数),model 简化为 Relationship (单数)。

创建关联:

class Student < ApplicationRecord
  has_many :releationships, dependent: :destroy
  has_many :teachers, through: :relationships
end
You need to Sign in before reply, if you don't have an account, please Sign up first.