Johnny Cash
Johnny Cash

Reputation: 5147

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.

Upvotes: 1

Views: 1871

Answers (1)

Eli Duke
Eli Duke

Reputation: 484

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.

Upvotes: 1

Related Questions