2016-06-22 24 views
0

我有以下型號:OrganisationValuationCapabilityRails協會多對多通過加入表

Organisation模型曾經有一個country字段,但它引起了我的注意,它可能有多個位置。

爲了解決這個問題,我可以創造一個Location模型,並添加OrganisationLocation之間的關係has_many,但是同樣的位置可以屬於多個組織。例如,組織X可能在英國,德國和美國有一個位置,組織Y可能在英國和德國有一個位置。

更大的問題在於Valuation描述在特定位置一個組織的估值爲特定的功能。那麼,在組織X中的位置Y中的估值可能是10,它可以爲組織X是8時位置Z.

眼下Valuationbelongs_to關聯設定既OrganisationCapability

class Valuation < ApplicationRecord 
    belongs_to :organisation 
    belongs_to :capability 
end 

要帳戶對於位置,我需要添加另一個關聯,但我正在尋找關於哪一個的提示。

接下來的問題是,如何設置我的關聯設定,所以我可以問這樣的問題:

什麼是組織X的有能力Ÿ在所有位置上的平均估值

是什麼organsiation x的對能力Ÿ位置z處估值

編輯

結束了與該many-to-many方法去,結束了該車型:

class Organisation < ApplicationRecord 
    has_many :memberships 
    has_many :locations, through: :memberships 
end 

class Location < ApplicationRecord  
    has_many :memberships 
    has_many :organisations, through: :memberships 
end 

class Membership < ApplicationRecord 
    belongs_to :organisation 
    belongs_to :location 
end 

現在的問題是這個鏈接到Valuation

+0

現在可以幫助整個答案,但如何使用複合主鍵進行評估? 含義,一個評估只能存在一個組織和一個位置? 而且,組織 - 位置關係應該是多對多 – lcguida

+0

另外,Capability與其他實體的關係又是什麼? – lcguida

+0

能力沒有關係,缺少Valution'belongs_to'能力 –

回答

0

OrganizationLocation之間的關係實際上是許多到很多。你需要的是一個連接表OrganizationsLocation,其表格爲organizations_locations,模式爲organization_idlocation_id

而且,估價實際上應該屬於OrganizationsLocation記錄。

class OrganizationsLocation < ActiveRecord::Base 
    belongs_to :organization 
    belongs_to :location 

    has_many :valuations 
end 

組織通過上述模型可以有很多估值。

class Organization < ActiveRecord::Base 
    has_many :organizations_locations 
    has_many :valuations, through: :organizations_locations 
end 

關於第一個問題「什麼是組織X的有能力Ÿ在所有位置上的平均估值」,你可以得到所有的估值與下面的代碼,並計算平均值:

x.valuations.where(capability_id: y.id) 

對於你的第二個問題: 「什麼是組織X的估值能力的Y位置Z」:

OrganizationsLocation.find_by(organization_id: x.id, location_id: z.id).valuations.find_by(capability_id: y.id) 

UPDATE:

由於您已經有一個加入表memberships,這與我建議的表organizations_locations相同,它可以滿足您的需求。

Valuation應該belongs_to a Membership而不是Organization

class Valuation < ActiveRecord::Base 
    belongs_to :membership 
    belongs_to :capability 
end 

x.valuations.where(capability_id: y.id) 

Membership.find_by(organization_id: x.id, location_id: z.id).valuations.find_by(capability_id: y.id) 
+0

謝謝!我對我的帖子進行了修改,因爲您的提案中似乎存在一些關聯。還爲連接表選擇了不同的名稱。 –

+0

請看我更新的答案。 –