我需要渲染一些基於我的模型的JSON,並且我需要包含一些相關的模型。這是我的代碼。渴望加載to_json包括
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
結果。然而,是這樣的:
{"user":{"admin":true,"email":"[email protected]","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}}]}}
正如你所看到的,所有相關的模型都缺少它們的屬性。只包括他們的ID密鑰。我假設這與急切的加載有關,我需要以某種方式將這些記錄加載到內存中,以便將它們的全部內容包含在to_json中,但是如何做到這一點?
謝謝!