【问题标题】:Conditional Active Model Serializer with Dates带日期的条件活动模型序列化器
【发布时间】:2020-11-03 23:20:30
【问题描述】:

我需要创建一个条件,以便日期小于当前日期的事件不会显示在 JSON 中,而只能看到即将发生的事件。

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 active-model-serializers


    【解决方案1】:

    创建自定义关联以仅根据日期过滤未来事件并在序列化程序中使用。

    在 Feeds 模型中,您将拥有如下所示的内容以及实际关联。

      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.
    

    并在 feed 序列化程序中访问自定义关联,

    class FeedSerializer < ActiveModel::Serializer
      
      has_many :future_events
     
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多