2010-11-10 15 views
9

मैं निम्नलिखित सेट अपरेल: inverse_of और एसोसिएशन एक्सटेंशन

class Player < ActiveRecord::Base 
    has_many :cards, :inverse_of => :player do 
    def in_hand 
     find_all_by_location('hand') 
    end 
    end 
end 

class Card < ActiveRecord::Base 
    belongs_to :player, :inverse_of => :cards 
end 

यह निम्न काम करता है मतलब है:

p = Player.find(:first) 
c = p.cards[0] 
p.score # => 2 
c.player.score # => 2 
p.score += 1 
c.player.score # => 3 
c.player.score += 2 
p.score # => 5 

लेकिन निम्नलिखित ही तरह से व्यवहार नहीं करता है:

p = Player.find(:first) 
c = p.cards.in_hand[0] 
p.score # => 2 
c.player.score # => 2 
p.score += 1 
c.player.score # => 2 
c.player.score += 2 
p.score # => 3 

d = p.cards.in_hand[1] 
d.player.score # => 2 

मैं :inverse_of संबंध विस्तार विधियों तक कैसे बढ़ा सकता हूं? (क्या यह सिर्फ एक बग है?)

उत्तर

4

यह काम नहीं करता है क्योंकि "in_hand" विधि में एक क्वेरी है जो डेटाबेस पर वापस जाती है।

inverse_of विकल्प की वजह से, कार्य कोड जानता है कि पहले से ही स्मृति में मौजूद वस्तुओं का उपयोग कैसे करें।

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

+1

ठीक है, नहीं है इसे "in_hand" विधि के साथ काम करने का कोई तरीका है? – Chowlett

7

मैं अगर (के रूप में मैं कर रहा हूँ) आप एसक्यूएल अनुकूलन अरेल द्वारा दी गई देने के लिए तैयार हैं एक समाधान पाया है और सिर्फ यह सब रूबी में करते हैं।

class Player < ActiveRecord::Base 
    has_many :cards, :inverse_of => :player do 
    def in_hand 
     select {|c| c.location == 'hand'} 
    end 
    end 
end 

class Card < ActiveRecord::Base 
    belongs_to :player, :inverse_of => :cards 
end 

विस्तार लिख रूबी में फिल्टर करने के लिए संघ का पूरा परिणाम के बजाय संख्या कम SQL क्वेरी करके, विस्तार के द्वारा लौटाए गए परिणाम :inverse_of साथ ठीक से व्यवहार:

p = Player.find(:first) 
c = p.cards[0] 
p.score # => 2 
c.player.score # => 2 
p.score += 1 
c.player.score # => 3 
c.player.score += 2 
p.score # => 5 

d = p.cards.in_hand[0] 
d.player.score # => 5 
d.player.score += 3 
c.player.score # => 8 
संबंधित मुद्दे