Frage

Ich habe eine komplexe Aktion innerhalb Controller, der mehrere Update-Anfragen an die Datenbank führt.

Wie kann ich diese Aktion machen wirkt wie Transaktion ohne strukturellen Refactoring?

War es hilfreich?

Lösung

MyModel.transaction do
  begin
    @model.update_stuff
    @sub_model.update_stuff
    @sub_sub_model.update_stuff
  rescue ActiveRecord::StatementInvalid # or whatever 
    # rollback is automatic, but if you want to do something additional, 
    # add it here
  end
end

Hier sind die Dokumentation für das Transaktionsverfahren .

Andere Tipps

Es ist möglich, alle Aktionen im Controller Transaktions macht sofort mit:

around_filter :transactional

def transactional
  ActiveRecord::Base.transaction do
    yield
  end
end
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top