2014-04-24 40 views
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?

回答

1

如果您查看api for habtm,可以選擇foreign_keyassociation_foreign_key。請嘗試以下

has_and_belongs_to_many :teachers, :class_name => 'Dancer', :join_table => :courses_teachers, :foreign_key => :course_id, :association_foreign_key => :teacher_id 

我不知道這是否會不經過foreign_key選項工作,但它可能會因此沒有它先試。

+0

工作原理(有/無foreign_key設置)。我一個人在想,雖然「has_and_belongs_to_many:teachers」應該在courses_teachers中查找並使用teacher_id,而不管class_name是否被指定?鍵入一些非常簡單/直接的東西似乎很重要。 – MotoPsycho

+0

對我來說,似乎一旦設置'class_name',導出'join_table'和'foreign_key'值的過程確實變得模糊不清。我認爲目前在這裏看到的行爲是理智的,如果這是值得的。 –

相關問題