gpt4 book ai didi

ruby-on-rails - 这是 Rails 3 中的竞争条件问题吗?

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:39 25 4
gpt4 key购买 nike

基本上我有这个 User 模型,它具有某些属性,比如“健康”和另一个 Battle 模型,它记录了用户之间的所有战斗。用户可以互相战斗,一些概率将决定谁获胜。战斗后双方都会失去健康。

所以在 Battle Controller 中,我执行了“CREATE”操作,

@battle = Battle.attempt current_user.id, opponent.id

对战模式中,

def self.attempt current_user.id, opponent_id

battle = Battle.new({:user_id => current_user.id, :opponent_id => opponent_id})

# all the math calculation here
...

# Update Health
...
battle.User.health = new_health
battle.User.save
battle.save

return battle

end

回到战斗 Controller ,我做了...

new_user_health = current_user.health

在战斗后获得新的生命值。但是我得到的值是旧的健康值(战斗前的健康值)。

有没有人遇到过这种问题???


更新

我只是补充

current_user.reload

行前

new_user_health = current_user.health

那行得通。问题解决了。谢谢!

最佳答案

看来您正在获取 current_user,然后更新 battle.user,然后期望 current_user 自动具有更新后的值。使用 Rails 的 Identity Map 可以实现这种类型的事情但您需要先阅读一些注意事项。

问题在于,即使这两个对象由数据库中的相同数据支持,您在内存中也有两个对象。要刷新信息,您可以调用current_user.reload

附带说明一下,这不会被归类为竞争条件,因为您没有使用多个进程来修改/读取数据。在此示例中,您正在读取数据,然后更新内存中不同对象的数据。如果您使用两个线程同时访问相同的信息,则可能会发生竞争情况。

此外,您应该使用 battle.user,而不是评论中提到的 Wayne 那样的 battle.User

关于ruby-on-rails - 这是 Rails 3 中的竞争条件问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8904384/

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