Delete some record and then rollback if condition fails in rails

750 Views Asked by At

Problem?

I have a Rails5 application. I have two models. Team and Players. The association is has_many & belongs_to in between them.

class Team < ApplicationRecord
  has_many :players
end


class Player < ApplicationRecord
  belongs_to :team
end

Now, I want to perform destroy players before updating the team model. The condition is like below

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

Note

In team_params, I have players_attributes, so each time if a new entry is there I need to remove all old entries and then @team.update_attributes will insert the entries in players.

Expectations

If @team.update_attributes(team_parmas) fails, then @team.players should be rolled back.

Things I tried

I tried adding Transactions in the first line of update method but it doesn't work.

1

There are 1 best solutions below

0
benjessop On BEST ANSWER

You can use a gem like paper trail to keep a history, but the nature of rails is to not be able to roll back transactions after committed. One way to mock this would be to keep the attributes in a transient collection of hashes and re-save them if you need the records once more. You could have logic like

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

Then if you need to 'roll back'

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

This will only work with basic attributes. If you have other model relations you will have to handle them with attributes also.