port5432
port5432

Reputation: 6371

JSON is not nested in rails view

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.

Upvotes: 0

Views: 122

Answers (1)

user229044
user229044

Reputation: 239270

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.

Upvotes: 1

Related Questions