ActiveModelSerializer:return 如果关联不存在,则为 nils 对象

ActiveModelSerializer: return object of nils if association does not exist

如果不存在关联记录,是否可以使用序列化器return nils 的关联?

例如

class CommentSerializer < ActiveModel::Serializer
  belongs_to :article

  def article
    # does not actually work
    super if super.present?

    Article.new
  end
end

这将允许像下面这样的内容 运行 而不会出现错误,而不管文章是否存在:

# javascript
comment.article.published_date

你可以

def article
  object.article || Article.new
end