Created
February 6, 2009 14:57
-
-
Save sprsquish/59426 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # using active record you can easily hit this common performance issue | |
| # | |
| class Parent | |
| has_many :children | |
| end | |
| class Child | |
| belongs_to :parent | |
| end | |
| # now this hits the db ***every*** time to find the child's parent | |
| # | |
| Parent.find(42).children.each do |child| | |
| child.parent | |
| end | |
| # we can fix this easily like so | |
| # | |
| class Parent | |
| has_many :children | |
| alias_method '__children__', 'children' | |
| def children | |
| __children__ | |
| ensure | |
| __children__.each{|child| child.parent = self} | |
| end | |
| end | |
| # now this doesn't hit the db at ***all*** for each child | |
| # | |
| Parent.find(42).children.each do |child| | |
| child.parent | |
| end | |
| # if you have the 'redef' gem installed this is even more compact, just do | |
| # | |
| class Parent | |
| has_many :children | |
| redef do | |
| def children | |
| returning(super){|children| children.each{|child| child.parent = self}} | |
| end | |
| end | |
| end | |
| # again this doesn't hit the db at ***all*** for each child | |
| # | |
| Parent.find(42).children.each do |child| | |
| child.parent | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment