Active record Query for has many through 关系

Active record Query for has many through relationship

我的 rails 应用中有一个 has_many through 关系,其关联如下:

class Car < ActiveRecord::Base
     has_many :car_fuel_types
     has_many :fuel_types , through: :car_fuel_types 
end

class FuelType < ActiveRecord::Base
    has_many :car_fuel_types
    has_many :cars , through: :car_fuel_types
end

class CarFuelType < ActiveRecord::Base
    belongs_to :fuel_type
    belongs_to :car
end

在我的应用程序中,用户 selects a fuel_type 并且在 selected fuel_type 的基础上,我必须过滤汽车。

因此,在汽车控制器中,我有 fuel_type_id 由用户作为参数传递,现在我需要 select 与 fuel_type 对应的汽车。

谁能帮我写一个活动记录查询来做这个?

编辑 1:

合并下面的答案,

我在我的汽车控制器的索引操作中使用了以下代码:

def index   
  @cars= FuelType.find(params[:fuel_type_id]).cars

respond_to do |format|
  format.html
  format.json { render json: @cars }
end

结束

我正在使用以下 curl 命令对其进行测试

 curl -i -H "Accept: application/json" -H "Content-type: application/json"  -H "X-User-Email: $EMAIL" -H "X-User-Token: $TOKEN" -X GET http://localhost:3000/cars.json\?id\=4

这是正在执行的查询

  SELECT  "fuel_types".* FROM "fuel_types" WHERE "fuel_types"."id" =  LIMIT 1  [["id", 4]]

  Car Load (0.7ms)  SELECT "cars".* FROM "cars" INNER JOIN "car_fuel_types" ON "cars"."id" = "car_fuel_types"."car_id" WHERE "car_fuel_types"."fuel_type_id" =   [["fuel_type_id", 4]]

  Completed 500 Internal Server Error in 85ms (ActiveRecord: 17.0ms)

   NoMethodError - undefined method `fuel_type_id' for #<Car:0x007f273923eb70>:

谁能帮我弄清楚为什么会出现这个错误?

这可能 return 您需要的是:

FuelType.find(fuel_type_id).cars