开发者

Mongoid references_many ids array population

I have a question regarding mo开发者_开发技巧ngoid id storage for references_many.

Suppose I have the following classes:

class A
  include Mongoid::Document
  field :name

  attr_accessible :name, :b_ids
  references_many :bs, :stored_as :array, :inverse_of :a
end

class B
  include Mongoid::Document
  field :name

  attr_accessible :name, :a_id
  referenced_in :a
end

If I do the following:

a = A.create(:name => "a1")
b = B.create(:name => "b1")
b.a = a

Should I expect the a.b_ids array to be an array that contains b's id?

The behaviour I am seeing is that b.a_id contains a's id, but a.b_ids does not contain b's id.

Is the id array on A's side supposed to be manually updated?

BTW, if I do a.bs << b, then a.b_ids gets updated correctly.


To answer my own question, the id arrays are not automatically set at the moment. This feature is planned to be included once the refactor branch of mongoid is released.

This info comes from this thread: http://groups.google.com/group/mongoid/browse_thread/thread/9ac74dc9a08a5fe2/d3a7c2404b67abfa

Until then, the ids have to be tracked manually.

An example would be:

class A
  include Mongoid::Document
  field :name

  attr_accessible :name, :b_ids
  references_many :bs, :stored_as :array, :inverse_of :a

  def add_b b
    bs << b
    self.save
  end

  def remove_b b
    b_ids.delete b.id
    b.save
  end
end

class B
  include Mongoid::Document
  field :name

  attr_accessible :name, :a_id
  referenced_in :a
end

a = A.create(:name => "a1")
b = B.create(:name => "b1")
b.a = a
a.add_b b
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜