How to convert records including 'include' associations to JSON

后端 未结 2 1700
终归单人心
终归单人心 2020-12-31 15:26

If I do something like:

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

then it only prints out t

相关标签:
2条回答
  • 2020-12-31 15:40

    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
    
    0 讨论(0)
  • 2020-12-31 15:54

    :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.

    0 讨论(0)
提交回复
热议问题