Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 设置默认模型序列化程序_Ruby On Rails_Ruby_Serialization_Active Model Serializers - Fatal编程技术网

Ruby on rails 设置默认模型序列化程序

Ruby on rails 设置默认模型序列化程序,ruby-on-rails,ruby,serialization,active-model-serializers,Ruby On Rails,Ruby,Serialization,Active Model Serializers,考虑到定义如下的对象模型和序列化程序: # models/thing.rb class Thing < ApplicationRecord end # serializers/thing_serializer.rb class ThingSerializer < ActiveModel::Serializer attributes :id, :name end 回报如期 {"id":3,"name":"rocket"} 但是,当我尝试将响应嵌套得更深时,如下所示: rend

考虑到定义如下的
对象
模型和序列化程序:

# models/thing.rb
class Thing < ApplicationRecord
end

# serializers/thing_serializer.rb
class ThingSerializer < ActiveModel::Serializer
  attributes :id, :name
end
回报如期

{"id":3,"name":"rocket"}
但是,当我尝试将响应嵌套得更深时,如下所示:

render json: { thing: @thing }
@thing
是序列化的,但不使用已定义的序列化程序(输出所有字段)

我的问题有两个方面:

  • 有没有一种干净的动态方法可以让序列化哈希对嵌套在其中的对象使用“默认”序列化程序,而不使用
    呈现json:{thing:ThingSerializer.new(@thing)}

  • 如果是这样,这是否也可以应用于集合序列化程序,这样对象就不必像


  • render json:{my_key:ThingSerializer::CollectionSerializer.new(@things)}

    试试看。作为_json方法,它应该调用serializer。呈现json:{thing:@thing.as_json}不幸的是,这与
    {thing:@thing}
    的工作方式相同,然后,您可以在模型类中重新定义这些方法(as_json/to_json),以仅显示所需的字段。
    render json: { thing: @thing }