Mongoid嵌入式文档父级未在after_initialize回调中设置

时间:2011-08-26 14:53:14

标签: mongoid

我正在尝试从after_initialize回调中引用嵌入文档的父对象。

这是我的设置的模型:

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

这会导致我不想要的行为:

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>

要获得所需的行为,我可以手动执行此操作:

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已经被设置,因为它是从人加载的,但事实并非如此。

是否有人知道这是否是所需的行为,如果是,你可以告诉我为什么吗? 如果这不是理想的行为,有人可以告诉我一个解决方法吗?

1 个答案:

答案 0 :(得分: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
相关问题