0

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.

3
  • This is because you're building them with each collection at the top level. That's what the line response = {:course => @course, :units => @units, :unit_layouts => @unit_layouts, :layout_fields => @layout_fields} does. Commented Oct 25, 2012 at 22:56
  • You also shouldn't be nesting two respond_to blocks. Commented Oct 25, 2012 at 22:58
  • You also shouldn't be re-finding the course inside your format :json block. You already found it up above, you only need the line @course = Course.find(params[:id]) once. Commented Oct 25, 2012 at 23:01

1 Answer 1

1

You need to use to_json with :include to include the associated records.

Here's a stab at it:

@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

It's probably not 100% correct, because you haven't included all the names of your associations, but I'm assuming that Unit has_many Layouts. To include the deeper nesting, add additional nested :includes.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi meagar that was exactly what I was looking for. Thanks very much for your time & multiple posts. It works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.