【问题标题】:Rails active_model_serializer conditional includeRails active_model_serializer 条件包含
【发布时间】:2016-01-19 00:48:11
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    belongs_to :user, if: :include_user?
    def include_user?
      current_user.admin?
    end
    

    【讨论】:

      猜你喜欢
      • 2011-08-18
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多