I'm writing my first Ruby on Rails application, and I'm having trouble managing record associations overall. In this question, specifically, I'd like to ask the community for suggestions on how to rollback recent saves to the database, based on the code below.
def create
@aula = Aula.create!(:name => aula_params[:name], :block_duration => aula_params[:block_duration], :rest_time => aula_params[:rest_time], :user_id => @current_user.id)
if @aula.valid?
JSON.parse(aula_params[:blocks]).each do |id, b|
@block = @aula.blocks.create!(:name => b["name"], :sequence_number => id)
if @block.valid?
b["workouts"].each do |id, w|
@block.block_workouts.create!(:workout_id => w["id"], :duration => w["duration"], :sequence_number => id, :repetitions_number => w["repetitions_number"])
end
else
render :json => { message: "Não foi possível criar essa aula", status: 500 }
end
end
render :json => { message: "Aula criada com sucesso", status: 200 }
else
render :json => { message: "Não foi possível criar essa aula", status: 500 }
end
end
This piece of code basically creates an "aula", that consists of multiple "blocks", that in turn are composed by multiple "workouts".
But, the problem is: suppose that the creation of a specific workout fails. In this case, the "aula" that was just created (and so the blocks and its related workouts) should be deleted. But I can't find a way of doing this in a concise, elegant manner.