ActiveModel Serializers:has_many在运行时有条件吗?

我使用rails(5.0.1)和active_model_serializers(0.10.2)。 我想以某种方式有条件地序列化has_many关联:

 class Question  :question end class Response  :responses end class QuestionSerializer < ActiveModel::Serializer attributes :id, :title, :created_at, :updated_at has_many :responses end class ResponseSerializer < ActiveModel::Serializer attributes :id, :title end 

我使用jsonapi并查询http://localhost:3000/api/questions/1我收到此回复:

回应1

 { "data": { "id": "1", "type": "questions", "attributes": { "title": "First", "created-at": "2017-02-14T09:49:20.148Z", "updated-at": "2017-02-14T13:55:37.365Z" }, "relationships": { "responses": { "data": [ { "id": "1", "type": "responses" } ] } } } } 

如果我从QuestionSerializer删除has_many :responses ,我会得到:

回应2

 { "data": { "id": "1", "type": "questions", "attributes": { "title": "First", "created-at": "2017-02-14T09:49:20.148Z", "updated-at": "2017-02-14T13:55:37.365Z" } } } 

如何在运行时有条件地获得Response-1Response-2 ? 我尝试了所有建议 – 不适用于AMS 0.10.2。 目前,条件只有这样:

 class QuestionSerializer < ActiveModel::Serializer attributes :id, :title, :created_at, :updated_at has_many :responses if true end 

要么:

 class QuestionSerializer < ActiveModel::Serializer attributes :id, :title, :created_at, :updated_at has_many :responses if false end 

在这2个案例中,我真的得到了Response-1Response-2 。 但这是硬编码的,我想将一个参数传递给序列化器或做一些类似的事情。

我该怎么办?

我想你已经回答了自己的问题。 如果您查看关联的AMS 文档,它会说支持条件。

据我所知,你只是一个错字

 class QuestionSerializer < ActiveModel::Serializer has_many :responses, if: false end 

attributes方法还支持if选项,如此处所述。

你的active_model_serializers版本是什么?

编辑 :我的答案也有错误。 我正在使用active_model_serializers (0.10.3)而且我能够做到

 class QuestionSerializer < ActiveModel::Serializer has_many :responses, if: -> { false } end 

if选项适用于方法,过程或字符串。 我认为你可以在运行时通过提供一个方法作为条件来决定。

 class QuestionSerializer < ActiveModel::Serializer attr_writer :should_render_association has_many :responses, if: -> { should_render_association } end # Usage: serializer = QuestionSerializer.new(question) serializer.should_render_association = false serializer.to_json # => no "responses" key 

感谢@gkats,我找到了答案(AMS 0.10.2):

 class QuestionSerializer < ActiveModel::Serializer attributes :id, :title, :created_at, :updated_at has_many :responses, if: -> { should_render_association } def should_render_association @instance_options[:show_children] end end class Api::ResponsesController < Api::ApplicationController def show render json: @response, show_children: param[:include_children] end end 

问题在于语法: if:在序列化程序中应该应用于块而不是函数。