2011-01-06 124 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"