Skip to content

Instantly share code, notes, and snippets.

@Bajena

Bajena/user_lazy.rb

Created Jan 27, 2019
Embed
What would you like to do?
# 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
You can’t perform that action at this time.