【问题标题】:Changing mongoid embeds_many association name更改 mongoid embeds_many 关联名称
【发布时间】:2012-07-27 20:14:31
【问题描述】:

使用 Rails 3.2 和 Mongoid 2.4。我有一个遗留模型,Organization,它嵌入了_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 而不是 Organization#organization_members)访问它?

【问题讨论】:

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


    【解决方案1】:

    embeds_many 有一个选项,称为store_as

    class Organization
      include Mongoid::Document
    
      embeds_many :members, 
                  class_name:"OrganizationMember", 
                  store_as: 'organization_members'
    end
    

    【讨论】:

    • 谢谢!我试过了,它响应一个 Invalid Option 错误。显然, store_as 仅在 Mongoid 3 (rdoc.info/github/mongoid/mongoid/master/Mongoid/Relations/…) 之后才相关。你知道这个的 2.4 等价物吗?
    • @Glenn:如果我坚持使用 2.4,我会重命名数据库中的旧字段。
    • 我想是时候升级了。我开始为我的用例寻找猴子补丁,咬紧牙关开始使用 Mongoid 3 似乎更有意义。感谢您的意见。欣赏它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多