您可以創建兩個連接表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:通過
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
道歉,我沒有通知你的答案。 而且,謝謝! 我試過你的第一個解決方案。但是,Event.lecturers和Event.students都會返回相同的結果。 我正在保存這樣的講師: event_in_db。講師<<用戶 此外,在連接表events_students和events_lecturers,我都嘗試USER_ID和student_id數據/ lecture_id作爲列。似乎沒有關係。 – 2013-12-25 22:50:18
看起來像第一個解決方案不起作用,因爲我忘了給'Event'模型添加'join_table'選項 – 2013-12-26 13:07:27