eager loading for to_json includes
I need to render some JSON based on my model, and I n开发者_如何学Goeed to include some associated models. Here's my code to do so.
def validate_candidate_id
matches = User.where(:wca_id => params[:wca_id])
if matches.any?
respond_to do |format|
format.html { redirect_to user_url(matches.first) }
format.json { render :json => matches.first.to_json(:include => {:candidate_results => {:include => [:checklist_item_results, :assessment]}}) }
end
else
respond_to do |format|
format.html { render :text => "Invalid ID" }
format.json { render :json => {}.to_json }
end
end
end
The result. however, is something like this:
{"user":{"admin":true,"email":"charlie@naturalguides.com","evaluator":true,"first_name":"Charlie","id":1,"last_name":"Mezak","wca_id":"999999","candidate_results":[{"id":5,"checklist_item_results":[{"id":45},{"id":46},{"id":47},{"id":48},{"id":49},{"id":50},{"id":51},{"id":52},{"id":53},{"id":54},{"id":55}],"assessment":{"id":1}}]}}
As you can see, all of the associated models are missing their attributes. Only their id keys are included. I'm assuming that this has to do with eager loading, that I need to somehow load these records into memory so that their entire contents will be included in the to_json, but how to do that?
Thanks!
I solved the issue by using as_json on my model. I had been using to_json, which was giving me incomplete results. From what I've just read, it seems that as_json is the preferred method for doing this, but I'd never even heard of it!
Have you tried using the ActiveRecord includes function i.e.
User.where(:wca_id => params[:wca_id]).includes(:candidate_results => [:checklist_item_results, :assessment])
精彩评论