Reputation: 7099
Each Car has has_many :comments
association
I have following method to return my cars:
class Api::V1::CarsController < Api::V1::BaseController
def recent
recent = Car.most_recent(params[:how_recent])
comments = recent.each{|r| r.comments} ## ??
respond_with(:recent => recent)
end
end
I get recent cars by:
curl -X GET http://cars.dev/api/v1/cars/recent -d "token=zzxWkB3SzDP3U1wDsJbY" -d "how_recent=20"
And I would like to get response like that:
"recent_with_comments":{"recent":[{"type":"ferrari","price":null,"user_id":78,"username":null,"comments":[{"id":1, "comment": "some text"},{"id":2, "comment": "some text 2"}]}]
Upvotes: 1
Views: 268
Reputation: 1414
When rendering as json you can pass some additional params as shown http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/
basic example:
class Api::V1::CarsController < Api::V1::BaseController
def recent
recent = Car.most_recent(params[:how_recent])
comments = recent.each{|r| r.comments} ## ??
respond_to do |format|
format.html
format.json { render recent.as_json(:include => :comments) }
end
end
end
Upvotes: 2
Reputation: 5437
comments = Comment.join(:car).merge(Car.most_recent(params[:how_recent]))
if u want custom json output use rabl gem
Upvotes: 0