Ich habe eine Aktion, die eine Reihe von Validierungen innerhalb einer jeden Schleife durchführt, in der Datenbank den Wert EventSubscription
in EventSubscription.create!
erstellt.Rails ActiveRecord Rollback mit Redirect nicht Umleiten
Wenn einige der Validierungen fehlschlagen, möchte ich die zuvor festgeschriebenen Transaktionen zurücksetzen. Um dies zu tun, lege ich den Code in einen ActiveRecord:Base.transaction
Block, aber wenn eine Validierung fehlschlägt und eine Ausnahme ausgelöst wird, wird der Rescue Block nicht einmal ausgeführt und daher nicht zur angegebenen Seite umgeleitet, und ich möchte dorthin umleiten Seite. Was kann hier falsch sein? Können Sie bitte helfen? Vielen Dank im Voraus!
Hier ist mein Aktionscode:
def download_subscriptions_file
ActiveRecord::Base.transaction(requires_new: true) do
begin
# ambiente para o qual vao ser criadas as subscricoes
@environment = Environment.find(params[:env_id])
uploaded_file = params[:file]
if uploaded_file
# Le e faz parse do ficheiro carregado
file = File.read(uploaded_file.path)
parsed_file = JSON.parse(file)
# logger.debug {parsed_file["eventSubscriptions"]}
# obtem as ARS e grava na tabela entities da BD do backoffice
parsed_file["eventSubscriptions"].each do |code, event|
# logger.debug {event}
# procura o evento correspondente, pois tem de existir na BD do BO
db_event = Event.find_by(display_name: code)
if !db_event
raise Exception.new("Não foi possivel importar o ficheiro pois não foi encontrado qualquer evento na BD com o nome #{code}")
end
event.each do |entity_code, subs|
# logger.debug {subs["_description"]}
# procura o tipo de endpoint correspondente, pois tem de existir na BD do BO
endpoint_type = EndpointType.find_by(description: subs["endpointId"])
if !endpoint_type
raise Exception.new('something bad happened!')
end
# procura a aplicacao no endpoint correspondente, pois tem de existir na BD do BO
endpoint_app = EndpointApp.find_by(description: subs["endpointAppId"])
if !endpoint_app
raise Exception.new('something bad happened!')
end
if entity_code != "default"
# procura a entidade correspondente, pois tem de existir na BD do BO
entity = Entity.find_by("code LIKE ?", "#{entity_code}%")
if !entity
raise Exception.new('something bad happened!')
end
active = "f"
# Verifica se a subscricao esta ou nao ativa para comparar com a que esta na BD e decidir se eh para mudar
if subs["status"] == "active"
active = "t"
end
# logger.debug { "entity->#{entity.code} #{entity.name}" }
# So cria/atualiza se nao existir a subscricao na BD para o ambiente em causa
entity_subs = EventSubscription.find_by(entity_id: entity.id, active: active, environment_id: @environment.id)
if !entity_subs
EventSubscription.create!(event_id: db_event.id, entity_id: entity.id, description: subs["_description"],
active: active, endpoint_type_id: endpoint_type.id, endpoint_app_id: endpoint_app.id,
environment_id: @environment.id)
end
end
end
end # parsed_file["eventSubscriptions"].each
respond_to do |format|
format.html {redirect_to env_event_subscriptions_path(env: @environment.id), notice: "Ficheiro de subscrições importado com sucesso para a BD do BackOffice no ambiente de #{@environment.name}." and return}
end
else
respond_to do |format|
format.html {redirect_to env_event_subscriptions_path(env: @environment.id), alert: 'Não foi selecionado qualquer ficheiro para importar.' and return}
end
end
rescue => exception
logger.error {"event_subscriptions_controller.download_subscriptions_file -> Ocorreu um erro ao importar o ficheiro de susbcricoes: #{exception.message}"}
respond_to do |format|
format.html {redirect_to env_event_subscriptions_path(env: @environment.id),
alert: "Ocorreu um erro ao importar o ficheiro de susbcrições: #{exception.message}" and return}
end
end
end
end