문제

컨트롤러 내부에 복잡한 작업이 있습니다. 데이터베이스에 여러 업데이트 쿼리를 수행합니다.

이 조치를 어떻게 만들 수 있습니까? 트랜잭션처럼 행동합니다 구조적 리팩토링없이?

도움이 되었습니까?

해결책

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

여기에 있습니다 거래 방법에 대한 문서.

다른 팁

컨트롤러 트랜잭션의 모든 작업을 다음과 같이 한 번에 만드는 것이 좋습니다.

around_filter :transactional

def transactional
  ActiveRecord::Base.transaction do
    yield
  end
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top