Skip to content

Instantly share code, notes, and snippets.

@sprsquish
Created February 6, 2009 14:57
Show Gist options
  • Select an option

  • Save sprsquish/59426 to your computer and use it in GitHub Desktop.

Select an option

Save sprsquish/59426 to your computer and use it in GitHub Desktop.
# 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