我有以下四种模式:
#models/team.rb
class Team < ActiveRecord::Base
has_many :locations
end
#models/location.rb
class Location < ActiveRecord::Base
belongs_to :team
has_many :relationships
has_many :contacts, through: :relationships
end
#models/relationship.rb
class Relationship < ActiveRecord::Base
belongs_to :location
belongs_to :contact
end
#models/contact.rb
class Contact < ActiveRecord::Base
has_many :relationships
has_many :locations, through: :relationships
end
我想在Team
模型上设置一个方法,我可以调用该方法来抓取该团队的所有关联contacts
。例如:
team = Team.find 1
this_teams_contacts = team.contacts
我知道我可以在team
模型中定义类似的东西,但它很详细并违反了demeter法则:
#models/team.rb
def contacts
contacts_ary = []
locations.each do |location|
# team should not know the implementation of how location goes about grabbing contacts, thus breaking the law of demeter on the following line:
location.contacts.each {|contact| contacts_ary << contact}
end
return contacts_ary
end
如何在遵守demeter定律的同时获取超出has_many :through
关联的关联?
答案 0 :(得分:2)
由于团队has_many :locations
和地点has_many :contacts
,我相信您只需将以下行添加到您的团队模型中:
has_many :contacts, through: :locations
然后,只需说出team.contacts
即可检索团队的联系人。当然,为了实现这一目标,将在幕后加入很多SQL,但鉴于您的数据模型,这在任何情况下都是不可避免的。