Search code examples
ruby-on-railsruby-on-rails-5active-model-serializers

Conditional Active Model Serializer with Dates


I need to make a condition so that events that have a date less than the current date are not displayed in the JSON and only see the upcoming events.

class EventSerializer < ActiveModel::Serializer
  attributes :end_date

  def end_date
    date_to_show = object.stop || (object.start + 1.day).beginning_of_day
    object.museum.time_zone ? ActiveSupport::TimeZone[object.match.time_zone].local_to_utc(date_to_show) : date_to_show
  end

class FeedSerializer < ActiveModel::Serializer
  
  has_many :events, if: -> { upcoming_event }, serializer: EventSerializer
 

  def upcoming_event
    ???
  end

  
end

Solution

  • Create a custom association to filter only future events based on a date and use that in the serializer.

    In Feeds model, you will have something like below along with the actual association.

      has_many :events, if: -> { upcoming_event }, serializer: EventSerializer
      has_many :future_events, -> { where(date < Date.today) }, class_name: 'Event' # Change the name, conditions as per your requirement.
    

    And access the custom association in the feed serializer,

    class FeedSerializer < ActiveModel::Serializer
      
      has_many :future_events
     
    end