您可以像这样创建两个连接表events_students
并events_lecturers
设置模型
class Event < ActiveRecord::Base
has_and_belongs_to_many :students, :class_name => 'User', :join_table => :events_students, :association_foreign_key => :user_id
has_and_belongs_to_many :lecturers, :class_name => 'User', :join_table => :events_lecturers, :association_foreign_key => :user_id
end
class User < ActiveRecord::Base
has_and_belongs_to_many :student_events, :class_name => 'Event', :join_table => :events_students, :association_foreign_key => :event_id
has_and_belongs_to_many :lecturer_events, :class_name => 'Event', :join_table => :events_lecturers, :association_foreign_key => :event_id
end
然后访问它:
Event.first.students
Event.first.teachers
User.first.student_events
User.first.lecturer_events
UPD。
另一种解决方案是使用 has_many :through
class User < ActiveRecord::Base
has_many :event_assignments
has_many :student_events, :through => :event_assignments, :source => :event, :conditions => {'event_assignments.type' => 'EventAssignment::Student'}
has_many :lecturer_events, :through => :event_assignments, :source => :event, :conditions => {'event_assignments.type' => 'EventAssignment::Lecturer'}
end
class Event < ActiveRecord::Base
has_many :event_assignments
has_many :students, :through => :event_assignments, :source => :user, :conditions => {'event_assignments.type' => 'EventAssignment::Student'}
has_many :lecturers, :through => :event_assignments, :source => :user, :conditions => {'event_assignments.type' => 'EventAssignment::Lecturer'}
end
class EventAssignment < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
class EventAssignment::Student < EventAssignment
end
class EventAssignment::Lecturer < EventAssignment
end
我将 STI 用于 EventAssignment 模型,因为如果您对不同类型的分配有不同的逻辑,它会很有用。但如果不需要它,只需使用另一个列名而不是type
连接模型来识别关系类型:
class User < ActiveRecord::Base
has_many :event_assignments
has_many :student_events, :through => :event_assignments, :source => :event, :conditions => {'event_assignments.kind' => 'student'}
has_many :lecturer_events, :through => :event_assignments, :source => :event, :conditions => {'event_assignments.kind' => 'lecturer'}
end
class Event < ActiveRecord::Base
has_many :event_assignments
has_many :students, :through => :event_assignments, :source => :user, :conditions => {'event_assignments.kind' => 'student'}
has_many :lecturers, :through => :event_assignments, :source => :user, :conditions => {'event_assignments.kind' => 'lecturer'}
end
class EventAssignment < ActiveRecord::Base
belongs_to :user
belongs_to :event
end