Ruby on rails 在habtm中定义类名时rails中出现意外行为
我有两个模特(当然还有舞者)。一门课程可以有许多舞蹈演员(学生)和老师(还有舞蹈演员)。教师可以是其他课程的学生 我对表格的定义如下:Ruby on rails 在habtm中定义类名时rails中出现意外行为,ruby-on-rails,Ruby On Rails,我有两个模特(当然还有舞者)。一门课程可以有许多舞蹈演员(学生)和老师(还有舞蹈演员)。教师可以是其他课程的学生 我对表格的定义如下: create_table "course_enrollments", :force => true do |t| t.integer "dancer_id", :null => false t.integer "course_id", :null => false t.datetime "at
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
并在课程教师表中将教师id重命名为舞者id
有更好的方法吗?如果您查看,可以选择外键
和关联外键
。试试下面的方法
has_and_belongs_to_many :teachers, :class_name => 'Dancer', :join_table => :courses_teachers, :foreign_key => :course_id, :association_foreign_key => :teacher_id
我不确定它在不通过
外键
选项的情况下是否能工作,但它可能会在不通过它的情况下先尝试。可以工作(设置了/不设置外键)。难道只有我一个人认为“有很多人:教师”应该在课程中查找教师,使用教师id,而不管是否指定了班级名称?对我来说,似乎一旦设置了class\u name
,派生join\u表
和外键
的值的过程就会变得模棱两可。我确实认为目前的行为是理智的,如果这值得的话。
has_and_belongs_to_many :teachers, :class_name => 'Dancer', :join_table => :courses_teachers, :foreign_key => :course_id, :association_foreign_key => :teacher_id