更改mongoid embeds_many关联名称

时间:2012-07-27 20:14:31

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid

使用Rails 3.2和Mongoid 2.4。我有一个遗留模型,即组织,embeds_many organization_members。它看起来像这样:

class Organization
  include Mongoid::Document

  embeds_many :organization_members
end

class OrganizationMembers
  include Mongoid::Document
  embedded_in :organization
end

我想要做的是将用于访问成员的方法从 organization.organization_members 更改为 organization.members 。这就是我所做的:

class Organization
  include Mongoid::Document

  embeds_many :members, class_name:"OrganizationMember"
end

class OrganizationMembers
  include Mongoid::Document
  embedded_in :organization
end

但是,现在organization.members返回一个空数组,organization.organization_members返回以前的文档,即使它没有定义church_members。

如何说服Mongoid使用以前的嵌入式集合名称并通过新的方法调用(Organization#members not Organization#organization_members)访问它?

1 个答案:

答案 0 :(得分:6)

embeds_many有一个选项,名为store_as

class Organization
  include Mongoid::Document

  embeds_many :members, 
              class_name:"OrganizationMember", 
              store_as: 'organization_members'
end