sprsquish (owner)

Revisions

gist: 59426 Download_button fork
public
Public Clone URL: git://gist.github.com/59426.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 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