2011-10-10 66 views
0

我试图确定一个特定组织有多少会议时间,但这并不像看起来那么容易,因为某些关系很复杂。Rails:与3个键的复杂HABTM关系?

class Meeting < ActiveRecord::Base 
    has_and_belongs_to_many :people 
end 

class Person < ActiveRecord::Base 
    has_any_belongs_to_many :meetings 
    has_and_belongs_to_many :positions 
end 

class Position < ActiveRecord::Base 
    has_and_belongs_to_many :people # b/c over time more than one person 
         may hold this position over time 
    belongs_to :organization 
end 

class Organization < ActiveRecord::Base 
    has_many :positions 
end 

,因为人们可能会随着时间改变位置(和组织),当有人到会,我也需要记在那个时候他们的立场,以便理货是准确的。因为HATBM连接表隐式处理(meetings_people),所以我无法跟踪位置。我如何在这种组合中添加位置,以及编写查询以获得每个组织的总会议时间的最佳方式是什么?

在此先感谢您提供的任何帮助或建议!

回答

1

has_many :through允许您使用正确的连接模型,而不是像habtm这样的暗示。你可以创建一个类似MeetingAttendance的课程,在那里你可以存储会议和参加者。然后你可以在你想要的模型上放置任何属性,包括position。然后,只需

Person has_many :meeting_attendances 
Person has_many :meetings, :through => :meeting_attendances 
Meeting has_many :meeting_attendances 
Meeting has_many :people, :through => :meeting_attendances 

class MeetingAttendance < ActiveRecord::Base 
    belongs_to :person 
    belongs_to :meeting 
end 

注意:您可能需要调整,由于我不知道的Rails如何处理“人”的多元化,但这是一般的想法。

Documentation here