Rails的对象关系和JSON渲染对象、关系、Rails、JSON

2023-09-09 21:58:35 作者:女人的小傲骨

免责声明,我不是很了解Rails的。我会尽量简洁。 考虑下面的模型关系的Rails:

类MODELA<的ActiveRecord :: Base的   belongs_to的:ModelB ... 一流的ModelB<的ActiveRecord :: Base的     的has_many:MODELA

当调用MODELA控制器返回的JSON的表演动作应该显示是对象B,其中的对象A的问题是一个孩子的孩子们ObjectAs。

所以,如果我有一个包含对象A的ID 1,2和3,然后访问的对象B:/modela/1.json

我应该看到:

{   modelb:{     ID:1,     MODELA:[插入MODELA JSON的ID的1,2和3]   } }

解决方案

在默认情况下,你得到的就只是这重新presents modelb 在上面的例子中JSON 。但是,你可以告诉Rails包括其它相关的对象,以及:

 高清输出
  @export_data = ModelA.find(PARAMS [:ID])
  respond_to代码做|格式|
    的format.html
    format.json {渲染:JSON => @ export_data.to_json(:包括=>:modelb)}
  结束
结束
 
javascript 中的window对象与其他对象的关系

您甚至可以告诉它排除某些领域,如果你不希望看到他们在出口:

 渲染:JSON => @ export_data.to_json(:包括=> {:modelb => {:除了=> [:created_at,的updated_at]}})
 

或者,只包括某些字段:

 渲染:JSON => @ export_data.to_json(:包括=> {:modelb => {:只=>:名}})
 

你可以嵌套这些深深为你需要(让我们说,ModelB也HAS_MANY ModelC):

 渲染:JSON => @ export_data.to_json(:包括=> {:modelb => {:包括=>:modelc}})
 

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