在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,但希望这会让您朝着正确的方向前进。