问题描述:

Is it possible to have a serializer return an association of nils if no associated record exists?

e.g.

class CommentSerializer < ActiveModel::Serializer

belongs_to :article

def article

# does not actually work

super if super.present?

Article.new

end

end

This would allow something like the following to run without error, regardless of article presence:

# javascript

comment.article.published_date

网友答案:

You could do

def article
  object.article || Article.new
end
相关阅读:
Top