2016-04-29 65 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 
相關問題