How to render an array.to_json with :include option in Rails?
In my controller I have :
def index
# Array of Task objects
@tasks = Task.get_tasks(current_user, params)
respond_to do |format|
format.html
# Sends correct JSON开发者_JS百科 but not including the 'author' object in it
# format.json { render :json => @tasks.to_json(:include => [:author]) }
# With this the JSON look correct but is interpreted as a string in the JavaScript code
format.json { render :json => @tasks.map { |e| e = e.to_json(:include => [:author]) } }
end
end
Do you know any 'clean' solution to properly pass the :include
option when rendering an array converted to JSON ?
EDIT
I am using MongoDB
EDIT (2)
I updated from mongoid (2.0.1)
to mongoid (2.0.2)
and it works.
Sorry for the trouble.
The to_json is redundant. I just tested it and with works with some similar code here using the syntax:
format.json { render :json => @tasks, :include => [:author] }
This is rails 3.0.7. This is also assuming that author is set as a belongs_to
of Task.
精彩评论