【问题标题】:How can I model a polymorphic, custom name relationship using Mongoid如何使用 Mongoid 建模多态的自定义名称关系
【发布时间】:2011-11-14 18:49:28
【问题描述】:

我试图在某些情况下使用模型的自定义名称来定义一系列模型关系,而在其他情况下它是本机名称。此外,模型可以被多个类引用,需要多态关系。

以下模型已简化(我已删除字段、附加关系等),但它们举例说明了我在避免创建继承模型的同时尝试生成的结构。

class Gallery
  include Mongoid::Document
  embedded_in :galleryable, polymorphic: true
end

class App
  include Mongoid::Document
  embeds_one  :about, class_name: 'Gallery', inverse_of: :galleryable
  embeds_one  :portfolio
end

class Portfolio
  include Mongoid::Document
  embedded_in :app
  embeds_many :galleries, as: :galleryable
end

我知道自定义关系嵌入的“子”也应该有一个class_name 定义和一个inverse_of:,但是如何在不需要显式定义关联类的情况下定义这些值?

【问题讨论】:

    标签: ruby-on-rails ruby mongoid models relationships


    【解决方案1】:

    您只需定义关联属性 ":as"

      class Gallery
        include Mongoid::Document
        embedded_in :galleryable, polymorphic: true
      end
    
      class App
        include Mongoid::Document
        embeds_one  :about, as: :galleryable
        embeds_one  :portfolio
      end
    
      class Portfolio
        include Mongoid::Document
        embedded_in :app
        embeds_many :galleries, as: :galleryable
      end
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      相关资源
      最近更新 更多