Skip to content

Instantly share code, notes, and snippets.

@Bajena
Created January 27, 2019 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bajena/4e57e5225aff9c02c2b7cc72da9d2f88 to your computer and use it in GitHub Desktop.
Save Bajena/4e57e5225aff9c02c2b7cc72da9d2f88 to your computer and use it in GitHub Desktop.
# app/models/post.rb
def user_lazy
BatchLoader.for(user_id).batch do |user_ids|
User.where(id: user_ids)
end
end
posts = Post.where(id: [1, 2, 3]) # SELECT * FROM posts WHERE id IN (1, 2, 3)
users = posts.map { |post| post.user_lazy }
users.each { |user| puts "#{user.name}" } # SELECT * FROM users WHERE id IN (1, 2, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment