Use attribute with condition in activemodel serializer

泄露秘密 提交于 2019-12-11 08:56:26

问题


class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :title
end

I use activemodel serializer to return title attribute with some conditions. Normally I can override title method but what I want is determine whether title attribute is returned or not with condition.


回答1:


I'm not sure exactly what your use case is, but maybe you can use the awesomely magical include_ methods! They are the coolest!

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :title

  def include_title?
    object.title.present?
  end
end

If object.title.present? is true, then the title attribute will be returned by the serializer. If it is false, the title attribute will be left off altogether. Keep in mind that the include_ method comes with it's own specific functionality and does things automatically. It can't be called elsewhere within the serializer.

If you need to be able to call the method, you can create your own "local" method that you can use within the serializer.

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :title

  def title?
    object.title.present?
  end
end

Again, not exactly sure what functionality you are looking for, but hopefully this gets you going in the right direction.



来源:https://stackoverflow.com/questions/31594472/use-attribute-with-condition-in-activemodel-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!