Advertisement
saasbook

database_abuses.rb

Aug 15th, 2013
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.74 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. # GOOD: preloading movies reviewed by fans avoids N queries in view.
  17.  
  18. # BAD: preload association but don't use it in view:
  19. - @fans.each do |fan|
  20.   %p= @fan.name
  21.   // BAD: we never used the :movies that were preloaded!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement