首页 > 解决方案 > 如何在版本化的 Active 模型序列化程序中制作 RESTful 根键?

问题描述

我通过脚手架生成了带有 user_controller 的 ruby​​ on rails 应用程序。

 # app/controllers/api/v1/users_controller.rb
 class Api::V1::UsersController < Api::V1::ApiController
  skip_before_action :verify_authenticity_token
  serialization_scope :view_context

   def show
     render json: @user
   end
 end

该模型

  # app/models/api/v1/user.rb
  class Api::V1::User < Api::V1::ApiRecord
    has_one_time_password

    validates_presence_of :phone
  end

和序列化器:

 # app/serializers/api/v1/user_serializer.rb
  class Api::V1::UserSerializer < ActiveModel::Serializer
    attributes :id, :phone, :first_name, :email, :dob, :last_name, :gender, :otp_code

    def otp_code
        object.otp_code
    end
  end

一切都很好,但我陷入了配置。/api/v1/users/2给我下面的回应。

   {
    "api/v1/user": {
        "id": 2,
        "phone": "999999999",
        "first_name": "Rajan",
        "email": "sample@h.com",
        "dob": "2000-01-01",
        "last_name": "Verma",
        "gender": "male",
        "otp_code": "503036"
      }
   }

你看到根密钥了吗?为什么它带有完整的命名空间?它应该是{ "user": { ...data } }唯一的。

我不想为这个微不足道的应用和补丁或黑客。我想我错过了在文档中找不到的任何配置。

请帮忙。

标签: ruby-on-railsjsonrubyactive-model-serializersserialization

解决方案


发生这种情况的原因是您的模型很Api::V1::User可能是由脚手架自动生成的。

你确定你的模型需要版本控制吗?

也许拥有一个模型User并将命名空间版本控制仅应用于您的控制器和路由对于您的应用程序来说就足够了。

如果您确实希望Vx模型也具有命名空间,那么您可以json_key按照Christian Bruckmayer的建议覆盖所有序列化程序或显式覆盖Api::V1::UserSerializer


推荐阅读