首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails::inverse_of和关联扩展

Rails::inverse_of和关联扩展
EN

Stack Overflow用户
提问于 2010-11-10 23:49:36
回答 2查看 7.5K关注 0票数 9

我有以下设置

代码语言:javascript
复制
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

这意味着以下工作:

代码语言:javascript
复制
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

但以下代码的行为与此不同:

代码语言:javascript
复制
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吗?)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-12 00:36:43

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

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

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

票数 4
EN

Stack Overflow用户

发布于 2010-11-12 17:23:16

如果(和我一样)你愿意放弃Arel授予的SQL优化,而只使用Ruby,我已经找到了一个解决办法。

代码语言:javascript
复制
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

通过编写扩展来过滤Ruby语言中关联的全部结果,而不是缩小SQL查询的范围,扩展返回的结果在:inverse_of中表现正确。

代码语言:javascript
复制
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
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4146278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档