2012-01-04 14 views
0

RoRで簡単な質問:2つのフィールドに同じモデルの外部キーを使用できますか?複数の固有フィールドに同じ外部キーを使用

たとえば、私は従業員です。 2つのフィールドが必要です:現在の私の店と、私は将来移動される店です。私のモデルでは、どのように2つのフィールドが同じforiegnキーであるが、異なる値を持つことができます。

Employeeモデルで

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

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

...例

説明するのは難しいですが、私は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を指定する必要があること、です。 EmployeeShopを参照するキーがある場合は、Employee belongs to a Shopとなります。

Commentには投稿のforeign_keyがある場合と同じですが、Comment belongs to a Postです。