【发布时间】:2020-07-11 17:36:54
【问题描述】:
有问题?
我有一个Rails5 应用程序。我有两个模型。 Team 和 Players。
它们之间的关联是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