如何获得 Rails 4 以在自定义序列化程序上使用嵌套根序列化 ActiveModel JSON?
How do I get Rails 4 to serialize ActiveModel JSON with a nested root on a custom serializer?
在 Rails 3 中,我的应用程序以模型名称作为根序列化了 ActiveModel 对象,例如:
{
"car": {
"id":29,
"make":"Kia",
"model":"Optima" }
}
配置于:
#config/initializers/wrap_parameters.rb
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = true
end
我将初始化程序设置 include_root_in_json 保持为 true,但是当我有自定义序列化程序 class 时,它不会再将模型作为 JSON 的根进行序列化:
#app/serializers/car_serializer.rb
class CarSerializer < ActiveModel::Serializer
attributes :id, :make, :model
end
序列化如下:
{
"id":29,
"make":"Kia",
"model":"Optima"
}
我希望它使用指定的根进行序列化,但需要自定义序列化程序从序列化中删除一些敏感字段。
如何实现 Rails 3 中 Rails 4 的默认行为,以便保持 API 向后兼容性?
通过删除自定义序列化程序 class 我能够将 JSON 的根节点作为模型名称。为了将模型上的敏感字段从序列化到 JSON 中排除,我在渲染
时使用了 except
子句
# app/controllers/car_controller.rb
respond_to do |format|
format.html # new.html.erb
format.json { render json: @order, except: [:sensitive_field_1, :sensitive_field_2] }
end
查看 Rails 4.0 docs -> ActiveModel -> 序列化程序 -> JSON。
在 Rails 3 中,我的应用程序以模型名称作为根序列化了 ActiveModel 对象,例如:
{
"car": {
"id":29,
"make":"Kia",
"model":"Optima" }
}
配置于:
#config/initializers/wrap_parameters.rb
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = true
end
我将初始化程序设置 include_root_in_json 保持为 true,但是当我有自定义序列化程序 class 时,它不会再将模型作为 JSON 的根进行序列化:
#app/serializers/car_serializer.rb
class CarSerializer < ActiveModel::Serializer
attributes :id, :make, :model
end
序列化如下:
{
"id":29,
"make":"Kia",
"model":"Optima"
}
我希望它使用指定的根进行序列化,但需要自定义序列化程序从序列化中删除一些敏感字段。
如何实现 Rails 3 中 Rails 4 的默认行为,以便保持 API 向后兼容性?
通过删除自定义序列化程序 class 我能够将 JSON 的根节点作为模型名称。为了将模型上的敏感字段从序列化到 JSON 中排除,我在渲染
时使用了except
子句
# app/controllers/car_controller.rb
respond_to do |format|
format.html # new.html.erb
format.json { render json: @order, except: [:sensitive_field_1, :sensitive_field_2] }
end
查看 Rails 4.0 docs -> ActiveModel -> 序列化程序 -> JSON。