Ruby On Rails:Netflix fast_jsonapi无法呈现其定义的属性

时间:2018-07-30 06:44:25

标签: ruby-on-rails ruby rubygems active-model-serializers fastjsonapi

当前我正在使用fast_jsonapi gem来处理API请求,而不是AMS。

但是当我想从attributes中删除某些字段或添加自定义字段时。

它不会出现,并且输出将返回与模型相关的所有字段。

licenses_controller.rb

class Api::V1::LicensesController < ApiController
  api :GET, "/v1/licenses", "get Listing licenses"
  formats ['json']
  def index
     render json: License.all, status: :ok
  end
end

license_serializer.rb

 class LicenseSerializer
  include FastJsonapi::ObjectSerializer
  attributes :code, :module
end

返回的输出

[  
   {  
      "id":6011,
      "code":"TBI-DA",
      "module":"Data Accessing",
      "amount":"1 lisensi server",
      "serial_number":"serial_6011",
      "created_at":"2018-07-30T11:13:22.002+07:00",
      "updated_at":"2018-07-30T11:13:22.002+07:00"
   },
   {  
      "id":6012,
      "code":"TBI-DAP",
      "module":"Dashboard Analytical Processing",
      "amount":"200 lisensi pengguna",
      "serial_number":"serial_6012",
      "created_at":"2018-07-30T11:13:22.018+07:00",
      "updated_at":"2018-07-30T11:13:22.018+07:00"
   }
]

预期输出:

[  
   {  
      "id":6011,
      "code":"TBI-DA",
      "module":"Data Accessing"
   },
   {  
      "id":6012,
      "code":"TBI-DAP",
      "module":"Dashboard Analytical Processing"
   }
]

我错过了一些配置吗?我认为,我遵循了基于gem文档的正确说明。

有人建议吗?我将非常感谢您的帮助:)

1 个答案:

答案 0 :(得分:2)

就像将Fast JSON API用作ActiveModelSerializersDocumentation没有任何有关升级ActiveModel的参考。因此,render json: License.all, status: :ok不会引起LicenseSerializer

再试一次:

render json: LicenseSerializer.new(License.all).serializable_hash, status: :ok