JSON is not nested in rails view

Posted by SeanGeneva on Stack Overflow See other posts from Stack Overflow or by SeanGeneva
Published on 2012-10-25T22:44:48Z Indexed on 2012/10/25 23:00 UTC
Read the original article Hit count: 198

Filed under:
|

I have a several models in a heirarchy, 1:many at each level. Each class is associated only with the class above it and the one below it, ie:

L1 course, L2 unit, L3 unit layout, L4 layout fields, L5 table fields (not in code, but a sibling of layout fields)

I am trying to build a JSON response of the entire hierarchy.

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

The code is bring back the correct values, but the units, unit_layouts and layout_fields are all nested at the same level under course. I would like them to be nested inside their parent.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about JSON