0
私はクラスUserとサブクラスのStudent and Teacher(STIを使用)を持っています。サブクラス間の関連付け(STI)
私は、生徒と教師の間にhas_and_belongs_to_manyの関連付けを作成したいと考えています。この関連付けを完了するためにどのように私が結合テーブルを作成できるか教えてください。
ありがとうございます!
私はクラスUserとサブクラスのStudent and Teacher(STIを使用)を持っています。サブクラス間の関連付け(STI)
私は、生徒と教師の間にhas_and_belongs_to_manyの関連付けを作成したいと考えています。この関連付けを完了するためにどのように私が結合テーブルを作成できるか教えてください。
ありがとうございます!
移行:
class CreateStudentsTeachersJoinTable < ActiveRecord::Migration
def change
create_table :students_teachers, id: false do |t|
t.integer :student_id
t.integer :teacher_id
end
end
end
先生モデル:
class Teacher < User
has_and_belongs_to_many :students, join_table: :students_teachers
end
学生モデル:
class Student < User
has_and_belongs_to_many :teachers, join_table: :students_teachers
end
興味があるだけ、学生と教師が右、独自のテーブルを持っていないのだろうか?私は彼らが単に "ユーザー"テーブルにエントリを持っていると思いますか?だから、student_idとteacher_idはどこから来たのですか? – user1175969
はい、単一の「ユーザー」テーブル。 デフォルトでは、habtm joinテーブルの外部キー名は、snake-caseに "_id"を加えたクラス名です。また、 "foreign_key"と "association_foreign_key"オプションを使用して指定することもできます。 –
これは、student_idが実際には "users"テーブルのuser_idであることを意味しますか? – user1175969