Created
May 23, 2021 16:58
-
-
Save UsamaAshraf/62dbe4739fe1f7dc28c6ec9644fb2fa3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PostSerializer < ActiveModel::Serializer | |
attributes :id, :title, :details, :author | |
def author | |
object.get_author_lazily do |author| | |
# Serialize the author after it has been loaded. | |
ActiveModelSerializers::SerializableResource | |
.new(author) | |
.as_json[:user] | |
end | |
end | |
end | |
class Post | |
def get_author_lazily | |
# The current post object is added to the batch here, | |
# which is eventually processed when the block executes. | |
BatchLoader.for(self).batch do |posts, batch_loader| | |
author_ids = posts.pluck(:author_id) | |
User.where(:_id.in => author_ids).each do |user| | |
modified_user = block_given? ? yield(user) : user | |
post = posts.detect { |p| p.author_id == user._id.to_s } | |
# 'Assign' the user object to the right post. | |
batch_loader.call(post, modified_user) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment