2016-04-29 7 views
0

私は航空会社のルーティング用のデータ構造を定義しています。予想される使用量はその別のテーブルのレコードにリンクするデザインフィールド

Route.find(1).from_airport # NRT 
Route.find(1).to_airport # KIX 
Route.find(2).from_airport # NRT 
Route.find(2).to_airport # TPE 

のようになります

しかし、私はfrom_airportフィールドまたはto_airportフィールドに文字列値を定義する必要はありません。

空港データは空港のテーブルで管理されます。

Ruby on Railsではどのように定義できますか?

これはルートテーブルのhas_oneロジックに属し、空港のbelongs_toロジックはありません。

モデル:(私の考えで)ルート

has_one :from_airport, foreign_key: "id??", class_name: "Route" 
has_one :to_airport, foreign_key: "id??", class_name: "Route" 

空港テーブル

id:1 name: NRT, city: TOKYO, country: JAPAN 
id:2 name: KIX, city: OSAKA, country: JAPAN 

ルートテーブル

from_airport: # it should NOT be a string, it should refers to a record in Airports table eg: airport (id:1) 
to_airport: # it should NOT be a string, it should refers to a record in Airports table eg: airport (id:1) 

答えて

0

は、これはあなたが探して何ですか?

# routes.rb 
belongs_to :from_airport, foreign_key: :from_airport_id, class_name: "Airport", primary_key: :id 
belongs_to :to_airport, foreign_key: :to_airport_id, class_name: "Airport", primary_key: :id 
関連する問題