2012-01-04 70 views
0

RoR中的快速問題:可能有兩個字段使用來自同一模型的外鍵嗎?用於多個唯一字段的相同外鍵

例如,我是一名員工。我想要兩個領域:我現在的商店,以及我將來會搬到的商店。在我的模型中,我怎麼能有兩個字段都是相同的foriegn鍵,但具有不同的值。

很難解釋......

一個例子

EMPLOYEE TABLE 
---------------------------------------------- 
Name  Current Shop ID  Next Shop ID 
John Doe 2      1 

SHOP TABLE 
---------------------------- 
ID   Shop Name 
1   Jims Tools 
2   Johns Tools 

Employee模式,我想這兩個Current ShopNext Shop是從店模式外鍵。

回答

0
class Employee < ActiveRecord::Base 
    has_one :current_shop, :class_name => Shop 
    has_one :next_shop, :class_name => Shop 
end 

class Shop < ActiveRecord::Base 
    belongs_to :current, :class_name => Employee 
    belongs_to :next, :class_name => Employee 
end 
0

如果外鍵不匹配的表名,您只需要指定它。但你可以擁有儘可能多的你想要的。

class Employee < ActiveRecord::Base 
    blongs_to :current_shop, :class_name => Shop, :foreign_key => "current_shop_id" 
    blongs_to :next_shop, :class_name => Shop, :foreign_key => "next_shop_id" 
end 

這裏要注意的重要一點是,你必須在有外鍵的模型,以指定belongs_to。如果Employee有一個引用Shop的密鑰,那麼Employee belongs to a Shop

就像Comment有一個Post的外鍵,然後是Comment belongs to a Post