중고 신입이 개발해보기..

after_update와 after_save의 차이는? 본문

Back-End /Ruby On Rails

after_update와 after_save의 차이는?

rootkaien 2024. 1. 23. 02:03

ChatGPT 3.5의 검색결과

 

루비 온 레일즈(Ruby on Rails)에서 `after_update`와 `after_save`는 두 가지 다른 콜백 메서드입니다. 이 두 메서드는 ActiveRecord 모델의 생명주기 동안 특정 시점에 코드를 실행하도록 설계되어 있습니다.

1. `after_update` 콜백:
   - `after_update`는 ActiveRecord 객체가 업데이트된 후에 호출됩니다.
   - 이 메서드는 레코드가 이미 존재하고 업데이트가 수행된 경우에만 호출됩니다.
   - 레코드가 처음 생성될 때는 `after_update`가 호출되지 않습니다.

   예를 들어:

   class YourModel < ApplicationRecord
     after_update :some_method

     private

     def some_method
       # 업데이트 후에 실행될 코드
     end
   end



2. `after_save` 콜백:
   - `after_save`는 ActiveRecord 객체가 데이터베이스에 저장된 후에 호출됩니다.
   - `after_save`는 레코드가 처음 생성될 때와 업데이트될 때 모두 호출됩니다.
   - 따라서 `after_save`는 `create` 및 `update` 동작 이후에 실행되는 콜백입니다.

   예를 들어:

   class YourModel < ApplicationRecord
     after_save :some_method

     private

     def some_method
       # 저장 후에 실행될 코드
     end
   end



따라서, `after_update`는 레코드가 이미 존재하고 업데이트될 때만 호출되고, `after_save`는 레코드의 생성 및 업데이트 이후 모두 호출된다는 차이가 있습니다.

'Back-End > Ruby On Rails' 카테고리의 다른 글

ruby on rails  (0) 2024.12.18
GPT가 알려주는 좌표로 거리 계산  (0) 2024.06.11
Rails로 서버 만들기  (0) 2023.04.25
ruby block  (0) 2022.11.30
Rails 6 Multiple database  (0) 2022.11.29
Comments