Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails::与关联扩展的逆__Ruby On Rails_Ruby_Ruby On Rails 3_Associations_Inverse - Fatal编程技术网

Ruby on rails Rails::与关联扩展的逆_

Ruby on rails Rails::与关联扩展的逆_,ruby-on-rails,ruby,ruby-on-rails-3,associations,inverse,Ruby On Rails,Ruby,Ruby On Rails 3,Associations,Inverse,我有以下设置 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 但

我有以下设置

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.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

如何使关系的
:逆\u扩展到扩展方法?(这只是一个bug吗?

它不起作用,因为“in_hand”方法有一个返回数据库的查询

由于选项的逆_,工作代码知道如何使用内存中已经存在的对象


如果(像我一样)您愿意放弃Arel授予的SQL优化,只需使用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

好的,有没有办法让它用“在手”的方法工作?
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
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