下面的解决方案。您确定要在学生和课程之间建立 one_to_many 连接吗 - 这似乎是明显的多对多。无论如何,重要的一点是第二联想。
class User
has_and_belongs_to_many :courses #or possibly better has_many :through, your call
has_many :taught_courses, :class_name => :course, :foreign_key => teacher_id
end
class Course
belongs_to :teacher, :class_name => :user, :foreign_key => teacher_id
has_and_belongs_to_many :users
end
更新:
上面的代码将创建两个关联。第一个是 habtm 关联,它需要另一个名为 courses_users 的表,其中包含两列(course_id 和 user_id,没有 id 列)。这会给你:
course.users #=> list of users taking the course
如果你愿意,你可以重命名这个关联写作:
has_and_belongs_to_many :students, :class_name => :user
第二个关联是 one_to_many,因此您可以通过以下方式使用它:
course.teacher #=> return single user or nil
user.taught_courses #=> return list of courses taught by given user
另一个更新:
通过两个表进行多个 habtm 关联(您可能更喜欢一个表,但是您需要使用 has_many :through,无论如何在这种情况下这可能会更好。架构:
create_table "courses" do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "courses_students", :id => false do |t|
t.integer "course_id"
t.integer "user_id"
end
create_table "courses_teachers", :id => false do |t|
t.integer "course_id"
t.integer "user_id"
end
create_table "users" do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
楷模:
class Course < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :teachers, :class_name => "User", :join_table => :courses_teachers
has_and_belongs_to_many :students, :class_name => "User", :join_table => :courses_students
end
class User < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :courses, :join_table => :courses_students
has_and_belongs_to_many :taught_corses, :join_table => :courses_teachers
end