1

I currently have a controller that returns JSON objects, that looks like this:

def getModels
  @vehicleModels = @vehicleModels.where(:vehicleMake_id => params[:vehicleMake])
  respond_with(@vehicleModels)
end

This works fine, and returns the following JSON:

[
{"created_at":"2011-06-22T15:49:06Z","id":1,"name":"A4","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":2,"name":"A5","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":3,"name":"A6","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":4,"name":"A8","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":5,"name":"TT","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":10,"name":"Touareg","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1}
]

The problem is that the JQuery dropdown I am trying to load the JSON into seems to be expecting a JSON root node. As such, loading the JSON above directly does not work. But if it has a root node, as follows, it works fine:

{"results":[
{"created_at":"2011-06-22T15:49:06Z","id":1,"name":"A4","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":2,"name":"A5","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":3,"name":"A6","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":4,"name":"A8","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":5,"name":"TT","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1},
{"created_at":"2011-06-22T15:49:06Z","id":10,"name":"Touareg","updated_at":"2011-06-22T15:49:06Z","vehicleMake_id":1}
]}

So the question is a simple one - how can I get rails to include a root node?

I should point out that I have attempted to do this by setting ActiveRecord::Base.include_root_in_json = true in my config, but that only added root nodes to each individual object, not one overall root node as I require.

Thanks!

1 Answer 1

3

You could do the following

 respond_with { :results => @vehicleModels }
Sign up to request clarification or add additional context in comments.

1 Comment

Can we use to_json with options for a fine control of json output?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.