Active Record No No's

1,138 views

Published on

Avoid the most common pitfalls of Active Record and reduce load on your database

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,138
On SlideShare
0
From Embeds
0
Number of Embeds
42
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Active Record No No's

  1. 1. Active Record No Nos Use your common sense
  2. 2. About me Patrick Hüsler Freelance developer Apple enthusiast Surfing and Kung Fu
  3. 3. AR Kool Aid No giant xml mapping file Dynamic finders Associations Inheritance Polymorphism ...
  4. 4. IT’S ALMOST WIZARDRY!!!!
  5. 5. BUT...
  6. 6. SO...
  7. 7. Be reasonable or ...
  8. 8. Code like this @user.friends.map {|friend| friend.id}
  9. 9. Or this @user.friends.sort_by{ |friend| [ friend.online? ? 1 : 0,friend] }
  10. 10. Or this friends.accepted.map{ |friend| friend.logs.visible_for(self) }.flatten
  11. 11. eventually leads to
  12. 12. THIS
  13. 13. We can do better ... Look at the generated SQL Create indices Let AR/SQL do the math (conditions,count,sum, named_scope, ...) Paginate, but paginate in SQL not on ruby collections Only fetch what you really need (:select => :id) Use :include (n + 1 problem)
  14. 14. Check SQL logs tail -f log/*.log Log to STDOUT in script/console Do it once in ~/.irbrc Use one of the query analyzer plugins Use profiling tools like New Relic RPM, FiveRuns TuneUp or Rack::Bug (Check railscast)
  15. 15. Where to look Iterations/calculations in views / partials Calculations on potentially big collections in ruby that can be done in SQL @user.friends.recent.sort_by{ |friend| [ friend.online? ? 1 : 0,friend] } Pagination on collection instead of SQL User.all.paginate(:per_page => 1, :page => 1)
  16. 16. Where to look Not eager loaded associations Post.all.each{|post| puts post.author.name} Classic n + 1 problem Post.all(:include => :author) Ruby is used for tasks that could be done with SQL Post.all.map(&:id) Instead of Post.all(:select => :id)
  17. 17. Image ressources http://www.gunaxin.com/wp-content/uploads/2009/05/kool_aid_man_glass.jpg http://www.thinkingfinance.net/blog/wp-content/uploads/2009/04/koolaidman.gif http://tux.crystalxp.net/png/chozo-mj-tux-gandalf-le-gris-1887.png http://icanhascheezburger.files.wordpress.com/2009/01/funny-pictures-cat-does-not-li http://midlifeslices.files.wordpress.com/2009/02/explosion-finger.jpg http://bmorearty.files.wordpress.com/2008/06/test-log-with-titles.png http://www.adoptedthemovie.com/wp-content/uploads/Picture_005.png http://comps.fotosearch.com/comp/TBZ/TBZ175/dynamite-magnifying-glass_~DYN014.jpg
  18. 18. Contact info Available for hire patrick.huesler@gmail.com https://www.xing.com/profile/Patrick_Huesler http://twitter.com/phuesler http://github.com/phuesler

×