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-1或Response-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-1或Response-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:
在序列化程序中应该应用于块而不是函数。
- 在activemodel序列化程序中使用带有条件的属性
- 渴望与Active Model Serializers加载关联
- 强制活动模型序列化程序返回关联
- <NoMethodError:#Record :: ActiveRecord_Relation的未定义方法`read_attribute_for_serialization':
- 控制器中的索引方法不适用于活动模型序列化程序
- Rails Active Model Serializer – has_many并访问父记录
- 如何在active_model_serializers中执行预先加载
- Active Model Serializer和Pundit在显示CRUD操作期间删除记录
- 版本控制ActiveModel :: Serializer