ruby-on-rails - 如何在版本化的 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 } }
唯一的。
我不想为这个微不足道的应用和补丁或黑客。我想我错过了在文档中找不到的任何配置。
请帮忙。
解决方案
发生这种情况的原因是您的模型很Api::V1::User
可能是由脚手架自动生成的。
你确定你的模型需要版本控制吗?
也许拥有一个模型User
并将命名空间版本控制仅应用于您的控制器和路由对于您的应用程序来说就足够了。
如果您确实希望Vx
模型也具有命名空间,那么您可以json_key
按照Christian Bruckmayer的建议覆盖所有序列化程序或显式覆盖Api::V1::UserSerializer
推荐阅读
- python - 如何在熊猫中有条件地对数据框进行切片
- javascript - setTimeout 不适用于 $(this)
- javascript - PHP 到 XMLHttpRequest SQL 删除
- highcharts - 如何在散点图上添加穿过原点(从正到负)的线 - highchart
- c# - 从另一个控制器创建指向控制器的 url 链接
- android - ionic build cordova android 给出错误“UnhandledPromiseRejectionWarning: Error: cmd: Command failed with exit code 1”
- css - 在导致输入大小变化的表单错误上添加边框
- r - 按不同的值删除一行
- c# - MVC 搜索功能实现
- c# - struct INotifyPropertyChanged 不适用于 ctor