I have a has_many through relationship in rails app. I is associated as follows:
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
In my cars_controller I want to get all to get all the Cars with a particular fuel_type, so I am writing the following logic in my cars_controller index action
def index
@cars = FuelType.find(params[:fuel_type_id]).cars
end
And I am using this curl command to test the result
curl -i -H "Accept: application/json" -H "Content-type: application/json" -X GET http://localhost:3000/cars.json\?fuel_type_id\=2
So this is giving me the list of cars with the selected fuel_type.
Now I want to add root to "cars" to the json response that I am getting, while trying to do that I came across active_model_serializers gem and read that I have to add the render block in my controller index aciton
So my new controller looks like:
def index
@cars = FuelType.find(params[:fuel_type_id]).cars
respond_to do |format|
format.html
format.json { render json: @cars }
end
end
hen I do this and try to the same curl command, it is giving me error in the render json :cars line.
The error that I am getting is:
NoMethodError - undefined method `fuel_type_id' for #<Car:0x007f36ff104a18>:
Can anyone tell me what should I do so that I get a root element in my response ?