【发布时间】:2014-04-24 05:21:52
【问题描述】:
我有两个模型(Course 和 Dancer)。一个课程可以有很多舞者(学生)和老师(也是舞者)。教师可以是其他课程的学生。
我将表格定义如下:
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),我希望 Course 的教师属性查找表 courses_teachers 并使用teacher_id 作为外键。相反,它正在寻找 course_dancers 和 dancer_id,大概是从将 class_name 设置为“Dancer”。这是设计使然还是错误?如果我这样做,我可以让它工作:
has_and_belongs_to_many :teachers, :class_name => 'Dancer', :join_table => :courses_teachers
并在 course_teachers 表中将 teacher_id 重命名为 dancer_id
有更好的方法吗?
【问题讨论】:
标签: ruby-on-rails