Ruby on rails 如何使用Mongoid为多态的自定义名称关系建模

Ruby on rails 如何使用Mongoid为多态的自定义名称关系建模,ruby-on-rails,ruby,mongoid,models,relationships,Ruby On Rails,Ruby,Mongoid,Models,Relationships,我试图在某些实例中使用模型的自定义名称定义一系列模型关系,而在其他实例中使用模型的本机名称。此外,模型可以被多个类引用,因此需要多态关系 下面的模型是简化的(我删除了字段、附加关系等),但它们举例说明了我试图生成的结构,同时避免创建继承的模型 class Gallery include Mongoid::Document embedded_in :galleryable, polymorphic: true end class App include Mongoid::Docume

我试图在某些实例中使用模型的自定义名称定义一系列模型关系,而在其他实例中使用模型的本机名称。此外,模型可以被多个类引用,因此需要多态关系

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

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 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
希望有帮助