Search code examples
ruby-on-railsrubyactive-model-serializers

Use attribute with condition in activemodel serializer


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.


Solution

  • 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.