简体   繁体   中英

RoR Activerecord: joining query with two associations that share a model

I have a model called flightleg:

class FlightLeg < ActiveRecord::Base
      ....
      belongs_to :departure_airport, :class_name => "Airport"
      belongs_to :arrival_airport, :class_name => "Airport"
end

And I want to do a query on it like this:

Flight.joins(:airline, flight_legs: [:departure_airport, :arrival_airport]).where('departure_airport.icao_code = YBBN')

Of course, this doesn't work. Here is a gist of the error message:

https://gist.github.com/emilevictor/b1b7d18d5cede597c6be

I am trying to figure out how to get it all to work nicely, and be able to refer to fields of the departure and arrival airports in my query.

There's no table 'departure_airports', but in the gist we see

 INNER JOIN "airports" ON "airports"."id" = "flight_legs"."departure_airport_id"

so can you try ('airports.icao_code = YBBN') ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM