Rails:搜索非常嵌套的关联

时间:2018-01-08 15:13:31

标签: ruby-on-rails rails-activerecord

我正在尝试找到一个到达机场IATA代码等于指定的航班的航班:

 create_table "flights", force: :cascade do |t|
    t.integer "route_id"
    t.datetime "departure"
    t.datetime "arrival"
    t.decimal "price"
    t.integer "airplane_id"
  end

  create_table "routes", force: :cascade do |t|
    t.integer "departure_airport_id"
    t.integer "arrival_airport_id"
  end

  create_table "airports", force: :cascade do |t|
    t.string "iata_code"
    t.string "icao_code"
    t.string "international_name"
    t.string "localized_name"
  end

从路线到机场的关联看起来像这样

class Route < ApplicationRecord
  belongs_to :arrival_airport, :class_name => "Airport"
  belongs_to :departure_airport, :class_name => "Airport"

机场班没有反过来。我试过这个

@search_results = Flight
                        .joins(:route)
                        .joins(:arrival_airport)  

1 个答案:

答案 0 :(得分:1)

你很亲密。

@search_results = Flight
                    .joins(route: :arrival_airport)
                    .where(airports: {iata_code: my_iata_code})

结帐Rails Query Guide了解更多详情。特别是12.1.3.1加入嵌套关联(单级)。