Ruby-on-rails Rails 对象关系和 JSON 渲染

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3462754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:01:28  来源:igfitidea点击:

Rails Object Relationships and JSON Rendering

ruby-on-railsrubyjsonactiverecord

提问by M. Ryan

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

免责声明,我对 Rails 知之甚少。我会尽量简洁。鉴于 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.

当调用 ModelA 控制器的 show 操作时,返回的 JSON 应该显示所有 ObjectA,它们是 ObjectB 的子级,而有问题的 ObjectA 是其子级。

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

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

I should see:

我应该看到:

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

回答by Rob Cameron

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

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

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

您可以根据需要将它们嵌套得尽可能深(假设 ModelB 也有_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...])

回答by Chau H?ng L?nh

If you want a more flexible approach to rendering json, you can consider using the gem jbuilder: https://github.com/rails/jbuilder

如果你想要更灵活的渲染json的方式,可以考虑使用gem jbuilder:https: //github.com/rails/jbuilder

It allows you to render custom attributes, instance variables, associations, reuse json partials in a convenient way.

它允许您以方便的方式呈现自定义属性、实例变量、关联、重用 json 部分。