我正在使用 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 为零。请帮助我如何解决它。提前致谢。