I am working on a Ruby on Rails project with ruby-2.5.0 and Rails 5. i am working on api part, i have used jsonapi-serializers gem in my app. I want to add conditional attribute in serializer.
Controller:
class RolesController < ApplicationController
def index
roles = Role.where(application_id: @app_id)
render json: JSONAPI::Serializer.serialize(roles, is_collection: true)
end
end
Serializer:
class RoleSerializer
include JSONAPI::Serializer
TYPE = 'role'
attribute :id
attribute :name
attribute :application_id
attribute :application do
JSONAPI::Serializer.serialize(object.application)
end
end
Here application is a model which has_many roles and roles belongs to application. I want to add application details in some conditions. I also tried like:
Controller:
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
Serializer:
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
But @instance_options is nil. Please help me how i can fix it. Thanks in advance.
In the jsonapi-serializers this is what is said about custom attributes: 'The block is evaluated within the serializer instance, so it has access to the object and context instance variables.'
So, in your controller you should use:
render json: JSONAPI::Serializer.serialize(roles, is_collection: true, context: { application: true })
And in your serializer you should use context[:application]
instead of @instance_options