当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails 4 - ActiveModelSerializer: return object of nils if association does not exist

问题描述:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: