트랜잭션 외부에서 예외를 catch해야합니다.
트랜잭션이 예외가 당신의 코멘트를 읽은 후 트랜잭션 블록을
begin
ActiveRecord::Base.transaction do
@var_types.each_with_index do |var,index|
var.save!
puts "saving"
end
end
rescue
puts "rescued"
end
UPDATE을 갈 때 롤백 할있다 : 당신이 내부 ActiveRecord::Rollback
올리면 : 여기에서 주목해야 할
ActiveRecord::Base.transaction do
raise ActiveRecord::Rollback unless @var_types.map(&:save).all? #passing here a block like { |res| res == true } is redundant.
redirect_to some_index_path, notice: "Everything saved"
end
render action: 'edit' # something didn't pass the validation, re-render the view
것들 트랜잭션 블록을 사용하면 복구 할 필요가 없습니다 (http://api.rubyonrails.org/classes/ActiveRecord/Rollback.html에서 문서 읽기)
누군가가이 같은 것을 할 수있는, 당신이 편안하게 생각하지 않는 경우는, 예외 던지기에 본사를 둔 흐름을 운전 안된다고 말할 수 있습니다
all_saved = false # need to define this var outside, or it will a block-level variable, visible only in the block
ActiveRecord::Base.transaction do
all_saved = @var_types.map(&:save).all?
raise ActiveRecord::Rollback unless all_saved
end
if all_saved
redirect_to some_index_path, notice: "Everything saved"
else
render action: 'edit' # something didn't pass the validation, re-render the view
end
출처
2014-12-22 11:18:55
Fer
내가 이것을 시도 할 것이다, 그러나이 캡처 것 모든 오류 및 첫 번째 오류를 직면에 종료하지? – Trancey
다음과 같이 작동하는 몇 가지 샘플 코드로 답변을 업데이트했습니다 : 예외가 발생하면 트랜잭션이 롤백되고 예외가 catch되고, 그렇지 않은 경우 모든 내용이 저장됩니다 – Fer
죄송합니다. code – Trancey