问题描述
我有几个层次结构模型,每个级别有1:许多.每个类仅与上面的类和下面的类关联,即:
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课程,L2单元L3单元布局,L4布局字段L5表字段(不在代码中,而是同级的布局字段)
L1 course,L2 unit,L3 unit layout,L4 layout fields,L5 table fields (not in code, but a sibling of layout fields)
我正在尝试构建整个层次结构的JSON响应.
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
代码将带回正确的值,但是在使用过程中,单位,unit_layouts和layout_fields都嵌套在同一级别.我希望它们被嵌套在其父内部.
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.
推荐答案
You need to use to_json
with :include
to include the associated records.
在这里刺伤
@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
.
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 :include
s.
这篇关于JSON没有嵌套在Rails视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!