0

当我在 Rails 5 API 中有 has_many/belongs_to 关系时,active_model_serializers我可以传递包含嵌套模型的选项。

def show
    render json: @post, include: ['comments']
end

也可以进行多层嵌套。

def show
    render json: @post, include: ['comments', 'comments.comment_likes']
end

我在任何地方都找不到有关向 include 语句添加条件的文档。有可能做这样的事情吗?

def show
    render json: @post, include: ['comments'] { top_contributor: true } 
end
4

1 回答 1

1

在 master(很快将成为 RC4)中,合并了一个 PR,允许在序列化程序级别进行以下操作:

belongs_to :user, if: :include_user?
def include_user?
  current_user.admin?
end
于 2016-01-20T22:26:46.793 回答