active_model_serializers icon indicating copy to clipboard operation
active_model_serializers copied to clipboard

Optional relationships

Open jacobbullock opened this issue 6 years ago • 5 comments

Purpose

With models that have many relationships, especially nested relationships, automatically including those relationships by default can make an otherwise fast query take a long time. Allowing an easy way to make relationships optional unless specifically requested through include is essential for performance

Changes

Only include relationships in the associations method if they are not defined as optional OR if they are optional and specified in the include request

There is also a small update to the .gitignore for excluding intelliJ project files

Caveats

This has worked perfectly for our existing needs including a number of polymorphic relationshisp, but may need further testing.

Related GitHub issues

#1865

Additional helpful information

In the following serializer:

class PostSerializer < ActiveModel::Serializer
    has_many :comments, :optional => true
    attributes :id, :title, :body
end

comments will not be the response unless asked for

render  :json => :post, :include  => "comments" # will include comments

render  :json => :post, # will only include post data

jacobbullock avatar Jun 06 '18 07:06 jacobbullock

Interesting idea. I assume this is for JSON:API? Would you consider using a 'minimal' serializer?

bf4 avatar Jun 22 '18 21:06 bf4

Not sure if it still exists in master, but I actually added exactly this in this PR.

(or use jsonapi suite and it's automatic 🙂 )

richmolj avatar Jun 22 '18 21:06 richmolj

@richmolj that PR looks interesting, that looks more thought out than this. I couldn't find anything about that while I was searching for how to do this. I'll take a look and see if this works in lieu of what i posted here. I was going to use the jsonapi suite, but i like the auto serializing that AMS does that I believe is not in any of the other serializers.

jacobbullock avatar Jun 22 '18 22:06 jacobbullock

@bf4 I am not quite sure I understand what you mean by 'minimal' serializer

jacobbullock avatar Jun 22 '18 22:06 jacobbullock

@bf4 I am not quite sure I understand what you mean by 'minimal' serializer

e.g.

class UserSerializer < ActiveModel::Serializer
  attribute :name
end
class UserPostsSerializer < UserSerializer
  has_many :posts
end
class UserAllTheThingsSerializer < UserSerializer
  has_many :posts
  belongs_to: :blog
  has_many :roles
  # etc
end

bf4 avatar Jun 25 '18 16:06 bf4