2012-10-25 69 views
0

我有几个模型在一个层次结构中,1:在每个层次上很多。JSON不嵌套在导轨视图中

L1当然, L2单元, L3单元布局, L4布局字段, L5表字段(未在代码,而是一个:每个类只与它上面的类和它下面的一个,即,相关联的兄弟的布局字段)

我想构建一个整个层次结构的JSON响应。

def show 
    @course = Course.find(params[:id]) 
    respond_to do |format| 
     format.html # show.html.erb 
     format.json do 
     @course = Course.find(params[:id]) 
     @units = @course.units.all 
     @unit_layouts = UnitLayout.where(:unit_id => @units) 
     @layout_fields = LayoutField.where(:unit_layout_id => @unit_layouts) 
     response = {:course => @course, :units => @units, :unit_layouts => @unit_layouts, :layout_fields => @layout_fields} 
     respond_to do |format| 
      format.json {render :json => response } 
     end 
     end 
    end 
    end 

代码返回正确的值,但单元,unit_layouts和layout_fields都在同一层次下嵌套。我希望他们嵌套在他们的父母。

+0

这是因为您正在为每个系列的顶层构建它们。这就是'response = {:course => @course,:units => @units,:unit_layouts => @unit_layouts,:layout_fields => @layout_fields}'的行。 – meagar

+0

你也不应该嵌套两个'respond_to'块。 – meagar

+0

你*也*不应该在'format:json'块中重新找到该课程。你已经在上面找到它了,你只需要'@course = Course.find(params [:id])'一次。 – meagar

回答

1

您需要使用to_json:include才能包含关联的记录。

这里有一个刺在它:

@course = Course.find(params[:id]) 

respond_to do |format| 
    format.html # show.html.erb 
    format.json do 
    render :json => @course.to_json(:include => { :units => { :include => :layouts } }) 
    end 
end 

它可能不是100%正确的,因为你没有包含在您的协会所有的名字,但我假设Unit的has_many Layouts。要包含更深的嵌套,请添加其他嵌套的:include

+0

谢谢,我会给你一个去。 – ardochhigh

+0

嗨*** meagar ***这正是我正在寻找。非常感谢您的时间和多个职位。它完美的作品。 – ardochhigh