2016-02-19 40 views
0

喜多關係,我想創建Rails的關係。許多到不同的對象id_s存儲在differen對象

我有戰士模型,法師模型和模型派。

我想建立這樣的關係:

warrior model can have_many factions 
mage model can have many factions. 
Faction model can have many warriors and mages 

如何創建戰士和法師的對象和派別對象之間的關係,將存儲id_s兩個戰士和法師屬於特定派系/派別?

所以,當我打電話:

faction.warriors I get warriors of specific faction. 
faction.mage I get mages of this faction 
warriors.faction I get the warrior faction. 
mage.faction I get the mage faction. 

我在想的多態關聯。但它只有一個所有者。

任何線索?

回答

0

如何創建戰士與法師對象與派系對象之間的關係,該對象將存儲屬於特定派系/派系的戰士與法師的id_s?

隨着has_and_belongs_to_many關係

Warrior 
    has_and_belongs_to_many :factions 

Mage 
    has_and_belongs_to_many :factions 

Faction 
    has_and_belongs_to_many :mages 
    has_and_belongs_to_many :warriors 
+0

我這個標記爲正確的,但最終我用的has_many雖然。但是這個答案仍然是正確的。 – Kazik

0

這不是真的清楚是否希望MANY_TO_MANY或的has_many關係。

但是從你這裏寫什麼:

faction.warriors我得到特定派系的勇士。 faction.mage我得到這個派別 warriors.faction的法師,我得到了勇士陣營。我得到了法師派。

看來,所有你需要的是一個簡單的關聯。如果這是正確的,你的課程應該是這樣的:

class Warrior < ActiveRecord::Base 
    belongs_to :faction 
end 

class Mage < ActiveRecord::Base 
    belongs_to :faction 
end 

class Faction < ActiveRecord::Base 
    has_many :warriors 
    has_many :mages 
end 

乾杯!