0

我正在使用 ruby​​-2.5.0 和 Rails 5 开发 Ruby on Rails 项目。我正在开发 api 部分,我在我的应用程序中使用了 jsonapi-serializers gem。我想在序列化程序中添加条件属性。

控制器:

class RolesController < ApplicationController
  def index
    roles = Role.where(application_id: @app_id)
    render json: JSONAPI::Serializer.serialize(roles, is_collection: true)
  end
end

序列化器:

class RoleSerializer
  include JSONAPI::Serializer

  TYPE = 'role'

  attribute :id
  attribute :name
  attribute :application_id

  attribute :application do
    JSONAPI::Serializer.serialize(object.application)
  end
end

这里的应用程序是一个模型,它有多个角色和角色属于应用程序。我想在某些情况下添加应用程序详细信息。我也尝试过:

控制器:

    class RolesController < ApplicationController
      def index
        roles = Role.where(application_id: @app_id)
        render json: JSONAPI::Serializer.serialize(roles, is_collection: true, params: params)
      end
    end

序列化器:

class RoleSerializer
  include JSONAPI::Serializer

  TYPE = 'role'

  attribute :id
  attribute :name
  attribute :application_id

  attribute :application do
    JSONAPI::Serializer.serialize(object.application), if: @instance_options[:application] == true
  end
end

但是@instance_options 为零。请帮助我如何解决它。提前致谢。

4

1 回答 1

2

jsonapi-serializers中,这是关于自定义属性的说法:“块在序列化器实例中进行评估,因此它可以访问对象和上下文实例变量。”

因此,在您的控制器中,您应该使用:

render json: JSONAPI::Serializer.serialize(roles, is_collection: true, context: { application: true })

在您的序列化程序中,您应该使用context[:application]而不是@instance_options

于 2018-10-26T19:38:25.480 回答