fast_jsonapi icon indicating copy to clipboard operation
fast_jsonapi copied to clipboard

Relationship, include and sparse fieldsets problem

Open phlegx opened this issue 5 years ago • 1 comments

Hi! I use the latest version (1.5) of the gem. I have the following construct:

# app/models/project.rb
class Project < ActiveRecord::Base
  belongs_to :owner,  class_name: 'Person'
  belongs_to :keeper, class_name: 'Person'
end

# app/serializers/project_serializer.rb
class ProjectSerializer
  include FastJsonapi::ObjectSerializer

  belongs_to :owner, serializer: :person
  belongs_to :keeper, serializer: :person
end

I serialize the project like this:

ProjectSerializer.new(Project.first, { 
  include: [:owner, :keeper],
  fields: { project: [:name, :owner, :keeper], owner: [:lastname], keeper: [:full_name] }
}).serializable_hash

The following output is produced:

{
   "data":{
      "id":"1",
      "type":"project",
      "attributes":{
         "name":"Test",
      },
      "relationships":{
         "owner":{
            "data":{
               "id":"1",
               "type":"owner"
            }
         },
         "keeper":{
            "data":{
               "id":"1",
               "type":"keeper"
            }
         }
      }
   },
   "included":[
      {
         "id":"1",
         "type":"person", /* always type person instead of owner */
         "attributes":{
           /* all attributes are listed here and not only attribute lastname !!! */
         },
         "relationships":{
            /* all relationships are listed here !!! */
         }
      },
      {
         "id":"1",
         "type":"person", /* always type person instead of keeper */
         "attributes":{
           /* all attributes are listed here and not only attribute full_name !!! */
         },
         "relationships":{
            /* all relationships are listed here !!! */
         }
      }
   ],
}

The problem

The sparse fieldset fields: { ..., owner: [:lastname], keeper: [:full_name] } don't work because in included JSON result there are two items with type person. So, all attributes and relationships are shown in included JSON result items. I have try out a mix of key and record_type but no one helps to solve this problem. Any idea?

phlegx avatar Mar 06 '19 12:03 phlegx

Seems you need the polymorphic option. https://github.com/Netflix/fast_jsonapi#customizable-options

everlast240 avatar Aug 05 '19 10:08 everlast240