views:

29

answers:

2

If I do something like:

result =  Appointment.find( :all, :include => :staff )
logger.debug { result.inspect }

then it only prints out the Appointment data, and not the associated staff data. If I do result[0].staff.inpsect then I get the staff data of course.

The problem is I want to return this to AJAX as JSON, including the staff rows. How do I force it to include the staff rows, or do I have to loop through and create something manually?

A: 

Check out ActiveRecord::Serialization and ActionController::Base (see section: "Rendering JSON")

def show
  @appointment = Appointment.find(:all, :include => :staff)
  respond_to do |format|
    format.html
    format.js { render :json => @appointment.to_json(:methods => [:staff]) }
  end
end
macek
+1  A: 

:include is an argument for to_json, not find. What you need to do in your controller is this:

def return_json
  @appointment = Appointment.find(:all)
  respond_to { |format|
    format.json { render :json => @appointment.to_json(:include => :staff) }
  }
end

You need to setup an association between Appointment and Staff for this to work.

Alex - Aotea Studios
:include is an argument to both ActiveRecord::Base#find and ActiveRecord::Serialization#to_json. They do different things: #find(:include) loads the associated data in one or more SQL queries, instead of the dreaded N+1 queries. #to_json(:include) marks one or more associations for inclusion in the returned JSON object. #to_xml behaves the same way.
François Beausoleil