假设您正在 Rails 中实现一个 REST API。提供集合时,您可能只想包含几个属性:
/people
但是在提供单一资源时,您希望包含所有属性:
/people/1
我不知道如何使用 ActiveModel::Serializers 来做到这一点,因为这些示例都使用了为每个模型定义一个序列化器(使用标准命名约定)并让 AMS 在 Controller 中自动使用正确的模式你这样做:
render json: @people
或:
render json: @person
最佳答案
您可以为同一模型拥有多个序列化器,例如
class SimplePersonSerializer < ActiveModel::Serializer
attributes :id, :name
end
和
class CompletePersonSerializer < ActiveModel::Serializer
attributes :id, :name, :phone, :email
end
一个 Controller 中的人的简单信息:
render json: @people, each_serializer: SimplePersonSerializer
其他人的完整信息:
render json: @people, each_serializer: CompletePersonSerializer
一个人的简单信息:
render json: @person, serializer: SimplePersonSerializer
一个人的完整信息:
render json: @person, serializer: CompletePersonSerializer
关于ruby-on-rails-3 - 如何使用 ActiveModel::Serializers 为同一模型实现多个不同的序列化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12485404/