Skip to content

Instantly share code, notes, and snippets.

@frostyblok
Created May 27, 2020 19:21
Show Gist options
  • Save frostyblok/fd97d5e0f2ec72f2350110516639faa9 to your computer and use it in GitHub Desktop.
Save frostyblok/fd97d5e0f2ec72f2350110516639faa9 to your computer and use it in GitHub Desktop.
The problem right now is due to N+1 queries, which means, our database is being flooded with 1, 000, 000 + 1 queries (Since we have a million subscriptions currently)—this is because Ruby on Rails lazy loading enabled by default. So to improve this, we eager load all the subscription entity with ‘includes()’. This allows to preload the plan associated data and thereby saving us some time. There are also other ways to eager load subscription entity with ‘eager_load()’ and ‘preload()’.
# lib/scripts/output_subscribers.rb

puts "email,monthly_price"

Subscription.includes(:plan).where.not(plans: {id: nil}).find_each do |subscription|

puts "#{subscription.email},#{subscription.plan.monthly_price}"

end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment