Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

ruby on rails 3 - How to implement multiple different serializers for same model using ActiveModel::Serializers?

Let's say you're implementing a REST API in Rails. When serving a collection, you might want to only include a few attributes:

/people

But when serving a single resource, you want to include all the attributes:

/people/1

I don't see how to do that using ActiveModel::Serializers, since the examples all use the pattern of defining one serializer per model (with a standard naming convention) and having AMS automatically use the right one in the controller when you do:

render json: @people

or:

render json: @person
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can have multiple serializers for the same model, e.g.

class SimplePersonSerializer < ActiveModel::Serializer
  attributes :id, :name
end

and

class CompletePersonSerializer < ActiveModel::Serializer
  attributes :id, :name, :phone, :email
end

simple info for people in one controller:

render json: @people, each_serializer: SimplePersonSerializer

complete info for people in another:

render json: @people, each_serializer: CompletePersonSerializer

simple info for a single person:

render json: @person, serializer: SimplePersonSerializer

complete info for a single person:

render json: @person, serializer: CompletePersonSerializer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...