我正在为航空公司路线定义数据结构。
预期用法将是那样的
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中定义它?
它是否属于Route表上的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 :(得分: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