2010-11-10 23 views
9

ho il seguente set-upRails:: estensioni inverse_of e di associazione

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 

Questo significa che le seguenti opere:

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 

Ma il seguito non si comporta allo stesso modo:

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 

Come è possibile estendere la relazione :inverse_of ai metodi di estensione? (È solo un bug?)

risposta

7

ho trovato una soluzione se (come me) si è disposti a rinunciare alla ottimizzazione SQL concessa da Arel e giusto fare tutto in Ruby.

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 

Scrivendo l'estensione per filtrare in Ruby i risultati completi della associazione, piuttosto che restringendo la query SQL, i risultati restituiti dalla estensione si comportano correttamente con :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 
Problemi correlati