Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # assumes class Moviegoer with has_many :movies, :through => :reviews
- # in controller method:
- @fans = Moviegoer.where("zip = ?", code) # table scan if no index!
- # in view:
- - @fans.each do |fan|
- - fan.movies.each do |movie|
- // BAD: each time thru this loop causes a new database query!
- %p= movie.title
- # better: eager loading of the association in controller.
- # Rails automatically traverses the through-association between
- # Moviegoers and Movies through Reviews
- @fans = Moviegoer.where("zip = ?", code).includes(:movies)
- # now we have preloaded all the movies reviewed by these fans.
- # in view:
- - @fans.each do |fan|
- - fan.movies.each do |movie|
- // GOOD: this code no longer causes additional queries
- %p= movie.title
- # BAD: preload association but don't use it in view:
- - @fans.each do |fan|
- %p= @fan.name
- // BAD: we never used the :movies that were preloaded!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement