Advertisement
saasbook

Database abuses

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