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 }