Rails 3 reply_to json with custom attributes / methods

In a rails application, I have an action that returns a json representation of a collection of different models. It looks something like this:

respond_to :json def index @cars = Car.all @vans = Van.all respond_with({ :cars => @cars, :vans => @vans }) end 

However, I want to configure the attributes and methods passed to the json object. Like a bit:

 respond_with({ :cars => @cars.to_json(:only => [:make, :model], :methods => [:full_name]), :vans => @vans }) 

Performing the above leads to the fact that the json representation of "cars" can be escaped as one large line, for example:

 { "cars":"[{\"car\":{\"make\":\"Ford\" ... etc "vans": [{"van":{"make":"Citreon" ... vans not escaped } 

Obviously, I am approaching this wrong. Can someone point me in the right direction?

+7
source share
1 answer

Since you are to_json in another Hash , I think you need to use as_json (which instead of String ) returns Hash ):

 respond_with({ :cars => @cars.as_json(:only => [:make, :model], :methods => [:full_name]), :vans => @vans }) 
+12
source

All Articles