Rails: :inverse_of and Association extensions Rails: :inverse_of and Association extensions ruby ruby

Rails: :inverse_of and Association extensions


I have found a workaround if (as I am) you're willing to give up the SQL optimisation granted by Arel and just do it all in Ruby.

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

By writing the extension to filter in Ruby the full results of the association, rather than narrowing down the SQL query, results returned by the extension behave correctly with :inverse_of:

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


It does not work because the "in_hand" method has a query that goes back to the database.

Because of the inverse_of option, the working code knows how to use the objects that are already in memory.

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