在activemodel序列化程序中使用带有条件的属性
class ProjectSerializer < ActiveModel::Serializer attributes :id, :title end
我使用activemodel序列化程序返回一些条件的title属性。 通常我可以覆盖标题方法,但我想要的是确定是否返回title属性与条件。
我不确定你的用例是什么,但也许你可以使用非常神奇的include_
方法! 他们是最酷的!
class ProjectSerializer < ActiveModel::Serializer attributes :id, :title def include_title? object.title.present? end end
如果object.title.present?
如果为true
,则序列化程序将返回title
属性。 如果为false
,则title
属性将完全保留。 请记住, include_
方法附带了它自己的特定function并自动执行。 它不能在序列化器中的其他地方调用。
如果您需要能够调用该方法,则可以创建自己的“本地”方法,以便在序列化程序中使用。
class ProjectSerializer < ActiveModel::Serializer attributes :id, :title def title? object.title.present? end end
同样,不完全确定您正在寻找什么function,但希望这会让您朝着正确的方向前进。
- 活动模型序列化程序belongs_to
- 如何在active_model_serializers中执行预先加载
- 使用active_model_serializers实现API版本控制的正确方法
- Ember Data属于协会(JSON格式?)
- ActiveModel Serializers:has_many在运行时有条件吗?
- 强制活动模型序列化程序返回关联
- 具有嵌入式ID和侧载的Ember-Data和Active Model Serializer的has_many配置
- Rails Active Model Serializer – has_many并访问父记录
- 使用active_model_serializers序列化权限(例如CanCan)