Docs Menu

데이터 모델에 대한 콜백 사용자 지정

이 가이드 에서는 Mongoid 모델에서 콜백을 구현 모델 인스턴스의 라이프사이클을 사용자 지정하는 방법을 학습 수 있습니다.

콜백은 객체 라이프사이클의 지정된 순간에 Mongoid가 트리거하는 메서드입니다. 객체의 상태 가 변경되기 전이나 후에 지정된 조치를 시작할 수 있습니다.

Mongoid는 Active Record의 많은 콜백을 구현합니다. 자세히 학습 액티브 레코드 문서에서 콜백을 참조하세요.

Mongoid는 문서 모듈을 구현 모델 클래스에서 다음 콜백을 지원합니다.

  • after_initialize

  • after_build

  • before_validation

  • after_validation

  • before_create

  • around_create

  • after_create

  • after_find

  • before_update

  • around_update

  • after_update

  • before_upsert

  • around_upsert

  • after_upsert

  • before_save

  • around_save

  • after_save

  • before_destroy

  • around_destroy

  • after_destroy

앞의 콜백 유형에 대해 자세히 학습 Rails API 문서에서 ActiveRecord::Callbacks 참조를 확인하세요.

최상위 문서 모델과 내장된 문서 모델 모두에서 콜백을 구현 수 있습니다.

참고

콜백 호출 동작

효율성 위해 Mongoid는 지속성 조치 수행한 문서 에 대해서만 콜백 호출합니다. 이 동작을 통해 Mongoid는 대규모 계층 구조를 지원 하고 문서 계층 구조 전체에서 콜백을 호출하지 않으므로 최적화된 원자성 업데이트를 효율적으로 처리하다 할 수 있습니다.

도메인 로직에 대한 콜백을 구현할 때는 예방 조치를 취하고 테스트 가능성을 확인해야 합니다. 이러한 설계는 체인의 콜백 실행이 중단될 때 예기치 않은 오류를 일으킬 수 있습니다. 배경 작업을 대기열에 추가하는 등 프로그램의 핵심 기능 이외의 교차 문제에 대해서는 콜백을 사용하는 것이 좋습니다.

모델 클래스에서 콜백을 구현 하고 등록해야 합니다. 일반 메서드, 블록 및 Proc 객체를 사용하거나 클래스 또는 모듈을 사용하는 사용자 지정 콜백 객체를 정의하여 콜백 등록할 수 있습니다.

이 예시 다음과 같은 방법으로 Contact 모델 클래스에 콜백을 등록하는 방법을 보여 줍니다.

  • Contact 인스턴스 MongoDB 에 저장되기 전에 process_phone 메서드를 트리거하는 before_save 클래스 메서드를 포함합니다. process_phone 메서드는 클래스에서 별도로 정의됩니다.

  • after_destroy 클래스 메서드를 포함하고 Contact 인스턴스 삭제될 때 차단 사용하여 메시지를 출력합니다.

class Contact
include Mongoid::Document
field :name, type: String
field :phone, type: String
# Creates a callback to clean phone numbers before saving
before_save :process_phone
protected
def process_phone
self.phone = phone.gsub(/[^0-9]/, "") if attribute_present?("phone")
end
# Creates a callback to send a message about object deletion
after_destroy do
p "deleted the contact for #{name}"
end
end

다음 코드는 콜백 작업을 보여주는 데이터 작업을 수행합니다.

Contact.create(name: 'Serena Atherton', phone: '999 555-3030')
# => `phone` field saved as '9995553030'
Contact.create(name: 'Zayba Haq', phone: '999 123?5050')
# => `phone` field saved as '9991235050'
Contact.first.destroy
# => Console message: "deleted the contact for Serena Atherton"

콜백 기능은 Active Support에서 제공하므로 set_callback 클래스 메서드 구문을 사용하여 콜백을 등록할 수도 있습니다. 다음 코드는 이 구문을 사용하여 aliases 배열 에 name 필드 의 원래 값을 저장하는 콜백 만드는 방법을 보여 줍니다.

class Contact
include Mongoid::Document
field :name, type: String
field :phone, type: String
field :aliases, type: Array, default: []
set_callback(:update, :before) do |document|
if document.name_changed?
document.push(aliases: document.name_was)
end
end
end
Contact.create(name: 'Xavier Bloom', phone: '4447779999')
Contact.first.update(name: 'Xav - coworker')
# Saved document in MongoDB:
# {"aliases":["Xavier Bloom"],"name":"Xav - coworker","phone":"4447779999"}

Mongoid는 다음과 같은 연관 콜백을 제공합니다:

  • after_add

  • after_remove

  • before_add

  • before_remove

모델 클래스에 연결 콜백 등록하면 다음 연결에서 문서 추가하거나 제거 때마다 호출됩니다.

  • embeds_many

  • has_many

  • has_and_belongs_to_many

각 연결의 옵션으로 연결 콜백을 지정합니다. 추가되거나 제거된 문서 지정된 콜백 에 매개변수로 전달해야 합니다.

다음 코드는 여러 SavedArticle 인스턴스를 임베딩하는 User 모델 클래스에 연결 콜백 등록하여 단일 인스턴스 에 대한 내장된 문서 수를 제한하는 방법을 보여 줍니다.

class User
include Mongoid::Document
field :username, type: String
# Registers the callback in the association statement
embeds_many :saved_articles, before_add: :send_message
protected
# Passes the association document as a parameter to the callback
def send_message(saved_article)
if saved_articles.count >= 10
p "you can't save more than 10 articles at a time"
throw(:abort)
end
end
end
class SavedArticle
include Mongoid::Document
embedded_in :user
field :url, type: String
end

Mongoid가 콜백을 실행 못하도록 하는 방법을 학습 액티브 레코드 문서에서 다음 참고 자료를 참조하세요.

Mongoid가 트랜잭션에서 콜백을 관리하는 방법에 대해 학습 트랜잭션 및 세션 가이드 참조하세요.

MongoDB 데이터에 액세스 하고 변경하는 방법을 학습 데이터와 상호 작용 가이드를 참조하세요.