2016-11-29 66 views
0

我正在構建一個非常簡單的導軌關聯並通過控制檯對其進行測試。我有一個用戶模型和一個課程模型。這些都是通過以下方式有關:導軌活動記錄關聯,使用從控制檯構建填充外鍵

class User < ApplicationRecord 
    has_many :courses, :dependent => :destroy 
end 

class Course < ApplicationRecord 
    belongs_to :teacher, :foreign_key => 'teacher_id', :class_name => 'User' 
end 

當通過控制檯測試我需要在課程表中的user_id列,以運行

User.first.courses.build 

但是,這樣做,我留下一個課程表中的空teacher_id。

我想知道是否有可能只在課程表中的teacher_id柱(沒有USER_ID這在我看來,冗餘),並填滿它自動運行

User.first.courses.build 

回答

0

發現錯誤的我的協會。

用戶模型應該通過teacher_id相關的課程:

has_many :taught_courses, :foreign_key => :teacher_id, :class_name => "Course", :dependent => :destroy 

這樣一切正常