Rails 对象关系和 JSON 渲染 [英] Rails Object Relationships and JSON Rendering

查看:20
本文介绍了Rails 对象关系和 JSON 渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明,我对 Rails 知之甚少.我会尽量简洁.鉴于 Rails 中的以下模型关系:

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,它们是 ObjectB 的子级,而有问题的 ObjectA 是其子级.

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.

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

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

我应该看到:

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

推荐答案

默认情况下,在上面的示例中,您只会获得表示 modelb 的 JSON.但是,您也可以告诉 Rails 包含其他相关对象:

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 }})

并且您可以根据需要将它们嵌套得尽可能深(假设 ModelB 也有_many ModelC):

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...])

这篇关于Rails 对象关系和 JSON 渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆