【问题标题】:Delete some record and then rollback if condition fails in rails如果条件在rails中失败,删除一些记录然后回滚
【发布时间】:2020-07-11 17:36:54
【问题描述】:

有问题?

我有一个Rails5 应用程序。我有两个模型。 TeamPlayers。 它们之间的关联是has_many & belongs_to

class Team < ApplicationRecord
  has_many :players
end


class Player < ApplicationRecord
  belongs_to :team
end

现在,我想在更新team 模型之前执行destroy 播放器。条件如下

def update
  @team.players.destroy_all if a
  ........
  if b
  .... some code.....
  elsif c
    @team.players.destroy_all
  end
  if @team.update_attributes(team_params)
    redirect_to teams_path
  else
  ... some code..
    render :edit
  end
end

注意

team_params,我有players_attributes,所以每次如果有新条目,我需要删除所有旧条目,然后@team.update_attributes将在players中插入条目。

期望

如果@team.update_attributes(team_parmas) 失败,那么@team.players 应该回滚

我尝试过的事情

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

【问题讨论】:

    标签: mysql transactions ruby-on-rails-5.1


    【解决方案1】:

    您可以使用像纸迹一样的宝石来保留历史记录,但 Rails 的本质是在提交后无法回滚事务。模拟这种情况的一种方法是将属性保存在临时的哈希集合中,如果您再次需要记录,请重新保存它们。你可以有这样的逻辑

    team_players = @team.players.map(&:attributes)
    

    那么如果你需要'回滚'

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

    这仅适用于基本属性。如果您有其他模型关系,您还必须使用属性来处理它们。

    【讨论】:

      猜你喜欢
      • 2014-06-17
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      相关资源
      最近更新 更多