Mysql 删除一些记录,然后在rails中条件失败时回滚

Mysql 删除一些记录,然后在rails中条件失败时回滚,mysql,transactions,ruby-on-rails-5.1,Mysql,Transactions,Ruby On Rails 5.1,问题? 我有一个Rails5应用程序。我有两个模型团队和玩家。 关联是在它们之间有许多&属于 class Team < ApplicationRecord has_many :players end class Player < ApplicationRecord belongs_to :team end 注意 在team\u params中,我有players\u属性,因此每次如果有新条目,我需要删除所有旧条目,然后@team.update\u attributes将

问题?

我有一个
Rails5
应用程序。我有两个模型<代码>团队和
玩家
。 关联是
在它们之间有许多&属于

class Team < ApplicationRecord
  has_many :players
end


class Player < ApplicationRecord
  belongs_to :team
end
注意

team\u params
中,我有
players\u属性
,因此每次如果有新条目,我需要删除所有旧条目,然后
@team.update\u attributes
将在
players
中插入条目

期望值

如果
@team.update\u attributes(team\u parmas)
失败,则
@team.players
回滚

我尝试过的事情


我尝试在
update
方法的第一行添加
Transactions
,但它不起作用。

您可以使用类似gem的书面记录来保存历史记录,但rails的本质是在提交后无法回滚事务。模拟这种情况的一种方法是将属性保存在散列的临时集合中,如果再次需要记录,则重新保存它们。你可以有这样的逻辑

team_players = @team.players.map(&:attributes)
然后如果你需要“回滚”

team_players.each do |team_player|
    TeamPlayer.create(team_player)
end
这仅适用于基本属性。如果您有其他模型关系,则还必须使用属性来处理它们

team_players.each do |team_player|
    TeamPlayer.create(team_player)
end