Glenn
Glenn

Reputation: 1102

Changing mongoid embeds_many association name

Using Rails 3.2, and Mongoid 2.4. I have a legacy model, Organization, that embeds_many organization_members. It looks something like this:

class Organization
  include Mongoid::Document

  embeds_many :organization_members
end

class OrganizationMembers
  include Mongoid::Document
  embedded_in :organization
end

What I'd like to do is change the method I use to access members from organization.organization_members to just organization.members. Here's what I've done:

class Organization
  include Mongoid::Document

  embeds_many :members, class_name:"OrganizationMember"
end

class OrganizationMembers
  include Mongoid::Document
  embedded_in :organization
end

However, now organization.members returns an empty array and organization.organization_members returns the previous documents, even though it church_members isn't defined.

How do I persuade Mongoid to use the previous embedded collection name and access it through the new method call (Organization#members not Organization#organization_members)?

Upvotes: 2

Views: 2940

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

There's an option to embeds_many, called store_as.

class Organization
  include Mongoid::Document

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

Upvotes: 6

Related Questions