2011-08-26 5 views
2

after_initialize 콜백 내에서 포함 된 문서의 부모 개체를 참조하려고합니다.몽고 이드 문서 부모가 after_initialize 콜백에 설정되지 않았습니다.

a = Person.new 
a.posts.build 
puts "after callback" 
p a.posts.first.person 

뱉어 :

[d][Moe:~]$ ruby test.rb 
in callback 
nil 
after callback 
#<Person _id: 4e57b0ecba81fe9527000001, _type: nil> 

이를 얻으려면

require 'mongo' 
require 'mongoid' 

connection = Mongo::Connection.new 
Mongoid.database = connection.db('playground') 

class Person 
    include Mongoid::Document 

    embeds_many :posts 
end 

class Post 
    include Mongoid::Document 

    after_initialize :callback_one 

    embedded_in :person, :inverse_of => :post 

    def callback_one 
    puts "in callback" 
    p self.person 
    end 
end 

이 내가 원하지 않는 동작이 발생할 것 : 여기

내 설정의 모형입니다 원하는 동작을 수동으로 수행 할 수 있습니다.

나에게주는 10
b = Person.new 
c = Post.new(person: b) 
puts "after callback" 
p c.person 

:

d][Moe:~]$ ruby test.rb 
in callback 
#<Person _id: 4e57b386ba81fe9593000001, _type: nil> 
after callback 
#<Person _id: 4e57b386ba81fe9593000001, _type: nil> 

그 대상 DB를에서로드되는가,이 경우 하나 person가 이미 설정 될 것이라고 생각 할 때마다 작동하지 않는 것을 가진 유일한 문제 , 그것은 사람에게서로드되고 있기 때문에,하지만 그렇지 않습니다.

이것이 바람직한 동작인지 누구에게 알 수 있습니까? 그렇다면 그 이유를 말해 줄 수 있습니까? 이것이 바람직한 동작이 아니라면 누구나 해결 방법을 말해 줄 수 있습니까?

+0

이 문제뿐만 아니라 Mongoid 3 지속 할 것으로 보인다. – Dex

답변

1

GitHub에서이 문제의 몇 가지 문제점이 있습니다 : #613, #815#900입니다.

Mongoid v2.2.0이 어제 발표되었지만 여전히 #900의 패치는 포함되어 있지 않습니다. 그래서 이것을 할 수있는 간단한 방법이 없습니다.

사용 사례에 따라 지연로드는 이미 충분 있습니다

class Post 
    include Mongoid::Document 

    embedded_in :person, :inverse_of => :post 

    # This won't work yet. 
    # 
    # after_build :init 
    # 
    # def init 
    # @xyz = person.xyz 
    # end 

    def xyz 
    @xyz ||= person.xyz 
    end 

    def do_something 
    xyz.do_some_magic 
    end 
end 
+0

해결 방법을 보내 주셔서 감사합니다. 아직 게으른로드를 시도하지 않았으므로 # 900 번 기다릴 것 같습니다. –

관련 문제