2011-03-31 5 views
5

I mongoid rails3mongid 포함 된 문서 콜백

class Address 
    include Mongoid::Document 
    embedded_in :person, :inverse_of => :address 
    after_validation :call_after_validation 
    before_validation :call_before_validation 
    before_update :call_before_update 
    after_update :call_after_update 
    after_create :call_after_create 
    before_create :call_before_create 

    field :address1 
    field :address2 

    private 
    def call_after_validation 
    puts "After validation callback fired." 
    end 

    def call_before_validation 
    puts "Before validation callback fired." 
    end 

    def call_before_update 
    puts "Before update callback fired." 
    end 

    def call_after_update 
    puts "After update callback fired." 
    end 

    def call_after_create 
    puts "After create callback fired." 
    end 

    def call_before_create 
    puts "Before create callback fired." 
    end 



end 

class Person 
    include Mongoid::Document 
    embeds_one :address 

    field :name 
end 

과 함께 다음과 같은 모델이 지금은 한 번에 한 사람과 주소를 저장하는 중첩 된 양식을 사용합니다.

그러나 결국

/전 주소에 대한/before_validation

뒤의 제안을 제외하고는 해고되지 않습니다/업데이트 콜백을 만들 이유 후/전 중첩 된 형태로 만들 때 콜백이 주소를 해고되지 않습니다/업데이트를 만들?

감사

+0

업데이트 : 거기에 어떤 식 으로든 또는 해킹 내가 mongoid 버전 2.0.0 beta19 – Gagan

답변

4

는 Mongoid 만 지속성 조치가 실행 된 문서의 콜백을 발생합니다.

따라서이 경우 Address가 Person에 포함되어 있기 때문에 유효성 검사 콜백 만 발생합니다. Person에 대해 생성/업데이트 콜백이 호출됩니다.

+0

을 사용하고 임베디드하는 docs before_save/after_save 콜백이 실행되거나 유사한 작업을 수행 할 수 있습니다. – Gagan

+0

그렇게 생각하지는 말고 Person 모델에 코드를 추가하여 원하는 것을 할 수 있습니까? – BenB

25
당신은 cascade_callbacks을 사용할 수 있습니다

: 진정한 부모 문서에 :

embeds_one : 아이, cascade_callbacks : 사실

+0

고마워요! 종종 이것은 셋팅이 필수적인 것은 아니지만 어떤 경우에는 매우 유용합니다. – fifigyuri

+0

고맙습니다. 매우 유용한 답변입니다. –

관련 문제