在 Relation 中添加新对象并一起渲染 JSON

时间:2021-04-22 13:16:08

标签: ruby-on-rails ruby rubygems

我有一个 SQL 搜索,它从 Active Record 返回一个关系。 我需要在这个返回中迭代并从它与其他表的关系中添加一个新对象,最后将它的 json 一起呈现。

例如:我有这个回报

example = #<ActiveRecord::Relation [#<Documento::Andamento id: 00001, nr_documento: 20211>, #<Documento::Andamento id: 00002, nr_documento: 20212>, #<Documento::Andamento id: 00003, nr_documento: 20213>, #<Documento::Andamento id: 00004, nr_documento: 21214>]>

lista = Array.new
  example.each do |andamento|
    movimento = andamento
    movimento.objeto_tramitacao_interesse = andamento.objeto_tramitacao.objeto_tramitacao_interesse //relatioship
    lista << movimento
    end

  render json: {autos_andamentos:[lista]}

我尝试过类似的方法但出错了

我想迭代并从关系表中添加一个新对象,并将其全部呈现为 json

1 个答案:

答案 0 :(得分:0)

如果这只是为了生成一些输出而更改实际记录,那么您可以在获取嵌套对象之前将对象转换为 JSON。这将允许您使用现有关系手动添加嵌套资源并将整个哈希附加到 lista 数组以构建您的有效负载,如下所示:

example = #<ActiveRecord::Relation [#<Documento::Andamento id: 00001, nr_documento: 20211>, #<Documento::Andamento id: 00002, nr_documento: 20212>, #<Documento::Andamento id: 00003, nr_documento: 20213>, #<Documento::Andamento id: 00004, nr_documento: 21214>]>
lista = Array.new

example.each do |andamento|
  movimento = andamento.as_json
  movimento["objeto_tramitacao_interesse"] = andamento.objeto_tramitacao.objeto_tramitacao_interesse

  lista << movimento
end

render json: { autos_andamentos: [lista] }

注意:使用 as_json 将返回一个带有字符串键的散列,这正是我们在这里需要的,而不是 to_json 将返回一个转义的 JSON 字符串。 >