如何将包含’include’关联的记录转换为JSON

如果我这样做:

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

然后它只打印出约会数据,而不是相关的人员数据。 如果我做结果[0] .staff.inpsect那么我当然得到了员工数据。

问题是我想将此作为JSON返回给AJAX,包括人员行。 如何强制它包含人员行,还是我必须循环并手动创建内容?

:includeto_json的参数,而不是find 。 您需要在控制器中执行的操作是:

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

您需要在约会和工作人员之间建立关联才能实现此目的。

查看ActiveRecord :: Serialization和ActionController :: Base (参见:“渲染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