2016-02-19 41 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 

干杯!