1
我有兩個模型(課程和舞者)。一門課程可以有許多舞者(學生)和教師(也包括舞者)。教師可以是其他課程的學生。在habtm中定義class_name時導致意外的行爲
我定義表如下:
create_table "course_enrollments", :force => true do |t|
t.integer "dancer_id", :null => false
t.integer "course_id", :null => false
t.datetime "attended_on", :null => false
end
create_table "courses", :force => true do |t|
t.string "name", :null => false
t.string "genre"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "courses_teachers", :id => false, :force => true do |t|
t.integer "course_id", :null => false
t.integer "teacher_id", :null => false
end
create_table "dancers", :force => true do |t|
t.string "first_name", :null => false
t.string "last_name", :null => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
及其類別:
class Dancer < ActiveRecord::Base
has_many :course_enrollments
has_many :courses, :through => :course_enrollments
has_many :teachers, :through => :courses
end
class Course < ActiveRecord::Base
has_many :course_enrollments
has_many :dancers, :through => :course_enrollments
has_and_belongs_to_many :teachers, :class_name => 'Dancer'
end
class CourseEnrollment < ActiveRecord::Base
belongs_to :dancer
belongs_to :course
end
根據指南(http://guides.rubyonrails.org/association_basics.html),我希望老師屬性課程,以查找表courses_teachers並使用teacher_id作爲外鍵。相反,它正在尋找courses_dancers和dancer_id,可能是將class_name設置爲'Dancer'。這是設計還是錯誤?我可以得到它的工作,如果我不是這樣做:
has_and_belongs_to_many :teachers, :class_name => 'Dancer', :join_table => :courses_teachers
和重命名teacher_id在courses_teachers表
是否有更好的方法來dancer_id?
工作原理(有/無foreign_key設置)。我一個人在想,雖然「has_and_belongs_to_many:teachers」應該在courses_teachers中查找並使用teacher_id,而不管class_name是否被指定?鍵入一些非常簡單/直接的東西似乎很重要。 – MotoPsycho
對我來說,似乎一旦設置'class_name',導出'join_table'和'foreign_key'值的過程確實變得模糊不清。我認爲目前在這裏看到的行爲是理智的,如果這是值得的。 –