0

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.

vinibrsl
  • 6,563
  • 4
  • 31
  • 44
awsm sid
  • 595
  • 11
  • 28

1 Answers1

2

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

Mihail Panayotov
  • 320
  • 2
  • 11
  • Thanks @Mihail i will accept your answer. Can you please help me in one more query i am using 'include_data: true' for association but it returns only id of the record it doesnot include other columns of the table. any idea? – awsm sid Oct 27 '18 at 12:06
  • @awsmsid Glad to have helped, regarding `include_data: true`, this is how it is supposed to work, to include only id and type in the returned json. In order retrieve the other columns of your associated object you should use links attributes. You can read about the jsonapi standard here [jsonapi](https://jsonapi.org/format/) – Mihail Panayotov Oct 27 '18 at 18:04
  • Thanks once again :) – awsm sid Oct 27 '18 at 18:31
  • Hi @Mihail Could you please check https://stackoverflow.com/questions/65240085/conditional-attributes-with-jsonapi-serializers-throwing-typeerror – awsm sid Dec 10 '20 at 18:46