2012-10-03 57 views
1

這有點棘手,所以如果您需要更多信息,請不要猶豫!導軌:鏈接兩個繼承相同型號的模型

我有兩個型號,StoreConsumer由兩種方式聯繫:

1/Store,並從同一個模型ProfileConsumer inherite,因爲他們有許多共同的屬性(名稱,地址,電子郵件,網頁, ...)。這裏是Rails AR代碼:

class Profile << ActiveRecord::Base 
    # Attributes and validation rules go here. 
end 

class Store << Profile 
end 

class Consumer << Profile 
end 

這是衆所周知的單表繼承(STI)。

2 /除了STI,StoreConsumer由許多與許多關係:

  • 商店有許多客戶(很多消費者)

  • 消費者是客戶許多商店

因爲我需要這個鏈接(商店 - 消費者)更多的屬性,我必須創建一個額外的模型,將鏈接他們:Client

這裏是我最後的AR模型:

class Profile << ActiveRecord::Base 
    # Attributes and validation rules go here. 
end 

class Store << Profile 
    has_many :clients 
end 

class Consumer << Profile 
    has_many :clients 
end 

class Client << ActiveRecord::Base 
    belongs_to :store 
    belongs_to :consumer 
end 

問題

使用STI不會產生STORE_ID和consumer_id ......我們只有PROFILE_ID(因爲一個真正的表Profile)。那麼,我該如何定位正確的具有store_id和client_id的Client行?

任何想法如何做到這一點?提前致謝。

+0

什麼你所描述的是不是性病。 STI是當兩種模型是某種事物的類型時:一輛車和一輛SUV是車輛的類型;貓和狗是動物的類型。在你的情況下,商店和消費者不是配置文件的類型。你有什麼(最好)是'has_one'關係:Store has_one Profile;消費者擁有一個配置文件。您可能正在尋找一個維護痛苦的世界,試圖將STI壓在您的域模型上。 –

+0

你知道了嗎? –

+0

@TimothyHunkele:我現在只是在嘗試它(似乎我們連接起來了!!)。在閱讀丹尼爾的解釋之後,我看到STI是否真的有必要。保持聯繫... – htaidirt

回答

3

我想你想要做的就是這樣。另外,我同意Daniel Wright的評論。

class Profile << ActiveRecord::Base 
    belongs_to :store 
    belongs_to :consumer 
end 

class Store << ActiveRecord::Base 
    has_one :profile 
    has_many :clients 
    has_many :consumers, :through => :clients 
end 

class Consumer << ActiveRecord::Base 
    has_one :profile 
    has_many :clients 
    has_many :stores, :through => :clients 
end 

class Client << ActiveRecord::Base 
    belongs_to :store 
    belongs_to :consumer 
end 

但是,如果你想使你有你可以做類似的工作是什麼:

class Profile << ActiveRecord::Base 

end 

class Store << Profile 
    has_many :clients, :foreign_key => 'store_id' 
    has_many :consumers, :through => :clients 
end 

class Consumer << Profile 
    has_many :clients, :foreign_key => 'consumer_id' 
    has_many :stores, :through => :clients 
end 

class Client << ActiveRecord::Base 
    belongs_to :store 
    belongs_to :consumer 
end 
+0

非常感謝Timithy的幫助和詳細的代碼!它工作非常好。 – htaidirt