2011-01-06 192 views
0

我有routes表,字段from_airport_idto_airport_idRails ActiveRecord協會

比方說:

route = Route.find(1) 

的問題是:如何定義ActiveRecord關聯,那route.from_airport就等於Airport.find(route.from_airport_id)和route.to_airport = Airport.find(路線.to_airport_id)?

換句話說:

from_airport_id => airport.id

to_airport_id => airport.id

我猜,查詢應該是:

route = Route.find(1).includes(:airports) 

但是怎麼辦我一次從同一張表中選擇兩條記錄?

回答

1
has_many :from_airports, :class_name => "AirPort", 
:foreign_key => "from_airport_id" 


has_many :to_airports, :class_name => "AirPort", 
:foreign_key => "to_airport_id"