-1

ユーザーとコース (「統計のコースを受講しています」のような「コース」) の間に関係モデルがあります。クラスには 1 人の教師 (ユーザー) と多くの生徒 (ユーザー) がいます。ユーザーは多くのクラスを教えることができますが、多くのクラスに登録することもできます。

私のモデルでこの関係を設定する正しい方法は次のようになると思います。

class User < ActiveRecord::Base
  has_many :taught_courses, class_name: "Course"
  has_and_belongs_to_many :enrolled_courses, class_name: "Course"
end

class Course < ActiveRecord::Base
  belongs_to :teacher, class_name: "User"
  has_and_belongs_to_many :students, class_name: "User"
end

しかし、データベースでこれを設定する方法がわかりません(これは初めてです)。

編集:

これに相当する移行があります:

def change
  create_table :courses_users do |t|
    t.belongs_to :course
    t.belongs_to :user
  end

  create_table :courses do |t|
    t.string :name
    t.integer :teacher_id

    t.timestamps
  end
end

しかし、コンソールで新しいユーザーを作成しようとすると、次のエラーが表示されますuser_id

irb(main):007:0> u.taught_courses.create(name: "Foo bar")
   (0.0ms)  SAVEPOINT active_record_1
   (0.1ms)  ROLLBACK TO SAVEPOINT active_record_1
ActiveRecord::UnknownAttributeError: unknown attribute: user_id

これはどこにあるべきuser_idですか?または、外部キーについてより具体的にする必要がありますか?

編集 2

foreign_key: "teacher_id"それが機能するためには、ユーザーとコースの間のhas_many関係についても指定する必要があることがわかりました。

誤解を招く質問で申し訳ありません。

4

1 に答える 1