我在我的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
在我的应用程序中,用户选择fuel_type,并根据所选的fuel_type我必须过滤汽车。
因此,在汽车控制器中,我有一个由用户作为参数传递的fuel_type_id,现在我需要选择与该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" = $1 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" = $1 [["fuel_type_id", 4]]
Completed 500 Internal Server Error in 85ms (ActiveRecord: 17.0ms)
NoMethodError - undefined method `fuel_type_id' for #<Car:0x007f273923eb70>:
任何人都可以帮我弄清楚为什么会发生这种错误?