eager loading for to_json includes

I need to render some JSON based on my model, and I need 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!

Answers


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!


Need Your Help

Soundcloud waveform nodes

api nodes soundcloud waveform

I was reading a article on soundcloud today about their waveforms and how they generate them by converting the highest volume point into a INT between 0 - 1.

Unrecognized URI: content://mms-sms/

android database sms mms

I want to get all MMS and SMS message records at the same time, but mms-sms seems to be an Unrecognized URI which I copy from android's source...