【问题标题】:postgres_ext-serializer each_serializer Rails 5 adding custom JSON meta datapostgres_ext-serializer each_serializer Rails 5 添加自定义 JSON 元数据
【发布时间】:2019-08-03 16:24:24
【问题描述】:

我正在使用 Rails 5.2.3、postgres_ext (3.0.0)、active_model_serializers (0.8.4),我正在尝试以

的格式呈现 JSON 数据
{
    total: 500,
    totalNotFiltered: 500, 
    rows: [
      ...
    ]
}

我可以接近,但我无法添加额外的自定义字段。

到目前为止我有

respond_to do |format|
    format.json { render json: @people, each_serializer: PersonSerializer, root: :rows, meta{total: 500, totalNotFiltered: 500}}
end

这给出了正确的根 :rows,但没有添加元数据。

postgres_ext gem 在正确获取 JSON 行方面做得很好,从 190ms av 下降到 25ms av,所以我想使用它。我已经尝试过 FastJSON (Netflix),但速度要慢得多,而且格式化生成的输出也不容易。

这里可能很简单,但我可以理解如何添加缺少的 2 个元素。请有想法或建议

【问题讨论】:

    标签: ruby-on-rails json active-model-serializers


    【解决方案1】:

    在 postgres_ext-serializers-0.0.3 gem 的 array_serializer.rb 中,我可以通过添加我需要的选项来破解这个 JSON 字符串,然后将其添加为临时解决方案的补丁。如果有人有更好的想法或方法,请指教。

    在控制器中(这是用于引导的顺便说一句)

     render json: @people, each_serializer: PersonSerializer, root: :rows, total: @people_count,  totalNotFiltered: Person.all.count}
    

    然后是serializer.rb

    module IncludeMethods
      def to_json(*)
        root = @options.fetch(:root, self.class.root)
        total = @options[:total]
        totalNotFiltered = @options[:totalNotFiltered]
        if ActiveRecord::Relation === object && root != false
           total = "{\"total\":\"#{total}\",\"totalNotFiltered\":\"#{totalNotFiltered}\","
          _postgres_serializable_array.sub('{', total)
        else
          super
        end
      end
    end
    

    它不是最好的,但它现在可以工作

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      相关资源
      最近更新 更多