【问题标题】:Add new object in Relation and render JSON together在 Relation 中添加新对象并一起渲染 JSON
【发布时间】:2021-04-22 13:16:08
【问题描述】:

我有一个 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

【问题讨论】:

    标签: ruby-on-rails ruby rubygems


    【解决方案1】:

    如果只需要生成一些输出并且更改实际记录,那么您可以在获取嵌套对象之前将对象转换为 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 字符串。

    【讨论】:

    • movimento["objeto_tramitacao_interesse"] = andamento.objeto_tramitacao.objeto_tramitacao_interesse 返回零
    • 那将是因为andamento.objeto_tramitacao.objeto_tramitacao_interesse 的值是nil。我只是重用您的代码示例,我对您的应用程序及其对象中​​存储的数据一无所知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多