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

When calling the show action of the ModelA controller the returned JSON should show all ObjectAs that are children of the ObjectB of which the ObjectA in question is a child of.

So if I have an ObjectB that contains ObjectA's of ID 1, 2 and 3 and then access: /modela/1.json

I should see:

{
  "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

You can even tell it to exclude certain fields if you don't want to see them in the export:

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

Or, include only certain fields:

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相关问答推荐

Jolt Transformation—如果子对象为空,则将父对象更新为空

如何获取brew list作为JSON输出

如何使用JQ有条件 Select 值

如何循环访问多个子数组并在单个JSON中检索数据点

如何使用GoFr返回XML响应?

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

使用JQ将对象数组转换为平面数组

如何在Android中解析带有动态键和可变对象名称的改装JSON响应?

用巨大的值更新SQL Server中的nvarchar(max)

使用 Power BI 中的 Deneb 视觉效果绘制面积图中的 X 轴日期

使用 jq,如何将两个属性构成键的对象数组转换为对象的索引对象?

使用 jq 从字符串列表开始创建对象

JSON 模式实际用于什么目的?

在循环中将变量添加到 bash 数组

一起使用 Argparse 和 Json

如何使用 Kotlin + Jackson 将 JSON 反序列化为 List

如何将 LinkedTreeMap 转换为 gson JsonObject

通过 RestAssured 中的 JsonPath 访问匿名数组的元素

Spring Security 和 JSON 身份验证

将 JSON 数据从 php 传递给 html-data 属性,然后传递给 Javascript