gpt4 book ai didi

ruby-on-rails - rails : :inverse_of and Association extensions

转载 作者:数据小太阳 更新时间:2023-10-29 06:49:43 25 4
gpt4 key购买 nike

我有以下设置

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

但下面的行为不一样:

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 关系扩展到扩展方法? (这只是一个错误吗?)

最佳答案

如果您(像我一样)愿意放弃 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

通过编写扩展以在 Ruby 中过滤关联的完整结果,而不是缩小 SQL 查询的范围,扩展返回的结果与 :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

关于ruby-on-rails - rails : :inverse_of and Association extensions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4146278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com