2017-03-13 36 views
0

SO ...如何将具有关联的活动记录转换为嵌套散列?

我写一些代码,将查询与各协会积极记录,并以类似的格式返回数据...

[{ 
    foo: { 
     id: ..., 
     foo_property: ... 
    }, 
    bar: { 
     id: ..., 
     bar_property: ... 
    } 
}, ...] 

...顶级活动记录它的组织都有时间戳和我想排除的其他领域。我知道attributesas_json但这些都不遵循关系(而是用foo_id和bar_id替换foo和bar)。我也知道AssociationReflection和它的能力,动态地找到关联,可以与一些复杂性执行我想要的,但理想...

我想要一个简单,优雅的方式来查询我的数据与此转换和属性过滤,即

Whatever.joins(:foos, :bars) 
     .eager_load(:foos, :bars) 
     .? # convert results to an array of hashes with association data (under appropriately named hash key) 
     .? # filter top level entries and association data to not have timestamps, etc. (select?) 

......谢谢!

+0

嗯,你能告诉我们的模型? – niceman

回答

2

我推荐使用ActiveModel::Serializers支持协会:

class WhateverSerializer < ApplicationSerializer 
    attributes :id, :other_attribute, :third_attribute 

    has_many :foos 
    has_many :bars 
end 

这允许您指定在最后JSON输出想要的属性(通过attributes),并让你整合协会(他们将使用FooSerializer和分别为BarSerializer)。

在相应的控制器,你可以只使用

render json: whatever 

和对象将自动通过串行缠绕。或者,如果你有Whatever对象的数组,你可以做到以下几点:

render json: Whatever.all, each_serializer: WhateverSerializer 
0

您可以使用一个语法像下面实现相同的行为:

假设一个嵌套的关联,如:巴兹有很多:酒吧, :bar有很多:foos

render json: Foo.includes(bar: :baz), 
include: {bar: {include: {baz: {only: [:attr_a]}}, 
only: [:attr_b]}}, only: [:attr_1, :attr_2, :attr_3] 

不过我也推荐使用ActiveModel::Serializers。当你有很多关联时,这个语法不清楚。

0

你可以尝试deep_pluck

Whatever.deep_pluck(
    foo: [:id, :foo_property, ...], 
    bar: [:id, :bar_property, ...], 
) 
相关问题