本文介绍了导轨: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

但下面不行为相同的方式:

But the following doesn't behave the same way:

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 关系延伸到扩展方法? (这只是一个bug?)

How can I make the :inverse_of relationship extend to the extension methods? (Is this just a bug?)

推荐答案

它不工作,因为in_hand的方法有一个查询可以追溯到数据库中。

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

由于inverse_of选项,工作code知道如何使用已经在内存中的对象。

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

这篇关于导轨:inverse_of和扩展协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:04