2012-07-27 40 views
2

使用Rails 3.2和Mongoid 2.4。我有一個遺留模型組織,即embeds_many organization_members。它看起來是這樣的:更改mongoid embeds_many協會名稱

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#organization_members)?

回答

6

有一個選項embeds_many,稱爲store_as

class Organization 
    include Mongoid::Document 

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

謝謝!我試過了,它以無效選項錯誤作出響應。顯然,store_as只有在Mongoid 3之後纔有意義(http://www.rdoc.info/github/mongoid/mongoid/master/Mongoid/Relations/Metadata:store_as)。你知道這個2.4等值嗎? – Glenn 2012-07-27 20:25:07

+1

@Glenn:如果我堅持2.4,我會重命名數據庫中的舊字段。 – 2012-07-27 20:34:13

+0

我猜是時候升級了。我開始爲我的使用案例尋找猴子修補程序,似乎咬住子彈並使用Mongoid 3更有意義。感謝您的輸入。欣賞它。 – Glenn 2012-07-27 21:46:56