简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM