saasbook

database_abuses.rb

Jul 11th, 2012
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.79 KB | None | 0 0
  1. # assumes class Moviegoer with has_many :movies
  2.  
  3. # in controller method:
  4. @fan = Moviegoer.find_by_email(email) # causes table scan if no index
  5.  
  6. # in view:
  7. - @fan.favorite_movies.each do |movie|
  8.   // BAD: each time thru this loop causes a new database query!
  9.   %p= movie.title
  10.  
  11. # better: eager loading of the association in controller.
  12. # Rails automatically traverses the through-association between
  13. # Moviegoers and Movies through Reviews
  14. @fan = Moviegoer.includes(:movies).find_by_email(email)
  15. # now we have preloaded all the movies this moviegoer reviewed.
  16.  
  17. # in view:
  18. - @fan.movies.each do |movie|
  19.   // GOOD: this code no longer causes additional queries
  20.   %p= movie.title
  21.  
  22. # BAD: preload association but don't use it in view:
  23. %p= @fan.name
  24. // BAD: we never used the :favorite_movies that were preloaded!
Advertisement
Add Comment
Please, Sign In to add comment