[英]ActiveModel::Serializers embed: :ids, include: true not sideloading data
我正在运行一个Rails 4.2 - AMS 0.9应用程序,我有(为了说明的目的)3个模型: Foo
has_one Bar
,has_many Baz
es。 我只在响应中获取ID,而不是侧载项。 是否有配置选项,或者我错过了什么?
我的AMS课程是:
class FooSerializer < ActiveModel::Serializer
embed :ids, include: true
has_one :bar, key: :bar ## For ember-data; it doesn't like "_id"
has_many :bazes, key: :bazes
attributes :id, :etc
end
StackOverflow上有很多关于AMS的主题,在发布之前我读了很多,但这让我完全糊涂了。
经过一系列的实验,我不得不在控制器中调用以下内容:
format.json { render json: ActiveModel::ArraySerializer.new(@foos, each_serializer: FooSerializer), root: :foos }
root: :foos
(顺便说一句,甚至不是“true”工作, self.root = true
或者self.root = :foos
串行器本身的self.root = :foos
)也是关键点。
@Ted的答案在数组上对我AciveModel::ArraySerializer
,但是当我尝试在show方法中序列化时,我当然不能使用AciveModel::ArraySerializer
。 在研究Ted的答案为何起作用的同时,我在AMS文档中遇到了这一点
当控制器不从ActionController :: Base继承时,请手动包含Serialization模块
class ApplicationController < ActionController::API
include ActionController::Serialization
end
链接: https : //github.com/rails-api/active_model_serializers/tree/0-9-stable#use-serialization-outside-of-actioncontrollerbase
由于我的rails app只是api,这就是我需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.