Disclaimer, I know very little about Rails. I'll try to be succinct. Given the following model relations in Rails:

class ModelA < ActiveRecord::Base
  belongs_to :ModelB

...

class ModelB < ActiveRecord::Base
    has_many :ModelA

调用ModelA控制器的show操作时,返回的JSON应该显示所有ObjectA,这些ObjectA是ObjectB的子对象,而ObjectA是ObjectB的子对象.

因此,如果我有一个ObjectB,其中包含ID为1、2和3的ObjectA,然后访问:/modela/1.json

我应该看到:

{
  "modelb": {
    "id": "1",
    "modela": [insert the ModelA JSON for ID's 1, 2 and 3]
  }
}

推荐答案

By default you'll only get the JSON that represents modelb in your example above. But, you can tell Rails to include the other related objects as well:

def export
  @export_data = ModelA.find(params[:id])
  respond_to do |format|
    format.html
    format.json { render :json => @export_data.to_json(:include => :modelb) }
  end
end

如果不想在导出中看到某些字段,甚至可以告诉它排除这些字段:

render :json => @export_data.to_json(:include => { :modelb => { :except => [:created_at, updated_at]}})

或者,只包括某些字段:

render :json => @export_data.to_json(:include => { :modelb => { :only => :name }})

And you can nest those as deeply as you need (let's say that ModelB also has_many ModelC):

render :json => @export_data.to_json(:include => { :modelb => { :include => :modelc }})

If you want to include multiple child model associations, you can do the following:

render :json => @export_data.to_json(include: [:modelA, :modelB, :modelN...])

Json相关问答推荐

如何创建生成两个不同对象的JSON数组的SQL查询?

NiFi QueryRecord处理器- Select 可选的JSON属性

VBA json按特定属性名称提取所有数据

JQ:获取该值的较短语法是什么

使用 JSON 和相对日期设置日历视图中 SharePoint 列表项的背景 colored颜色 格式

XSLT 3.0 Json-to-xml,json 包含 html struct

Jolt规范:将嵌套数组中的null元素移除

如何在 wso2 中组合 2 个 json 有效负载?

如何从条带订阅响应对象中正确获取 struct 项?

如果 jq 数组中的字符串是对象或字符串,则获取值

如何解决名为 null 的map值

JSON Schema 与 XML Schema 的比较及其future

使用 JSON 的 javascript 深拷贝

使用 API 搜索维基百科

有没有办法使用 Jackson 将 Map 转换为 JSON 表示而不写入文件?

嵌套 JSON:如何向对象添加(推送)新项目?

未调用 npm package.json 脚本

获取一个数字的 PHP 对象属性

PHP json_encode json_decode UTF-8

如何对 jq 中的 map 数组中的值求和?