Created
May 23, 2021 16:57
-
-
Save UsamaAshraf/863be4a75387c2929a1f0b6be52be7bb 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 | |
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| | |
post = posts.detect { |p| p.author_id == user._id.to_s } | |
#'Assign' the user object to the right post. | |
batch_loader.call(post, user) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment