Ruby on rails 3 Rails 3通过mongoid适配器使用MongoDB-有没有办法在不使用单表继承的情况下共享属性规范?

Ruby on rails 3 Rails 3通过mongoid适配器使用MongoDB-有没有办法在不使用单表继承的情况下共享属性规范?,ruby-on-rails-3,mongodb,mongoid,sti,Ruby On Rails 3,Mongodb,Mongoid,Sti,可能是一个令人困惑的标题,但不知道该怎么说。举例说明应该更清楚。我有许多不同的模型,它们共享许多相同的属性。因此,在每个模型中,我必须指定相同的属性,然后指定特定于特定模型的属性 有没有什么方法可以创建一些列出这些基本属性的类,然后从该类继承而不使用单表继承?因为如果我将所有共享属性和Mongoid包含放在一个模型中,并从其他模型中的基础模型继承,那么STI将被强制执行,并且我的所有模型都存储在一个mongodb集合中,由“_type”字段区分 这就是我所拥有的: class Model_1

可能是一个令人困惑的标题,但不知道该怎么说。举例说明应该更清楚。我有许多不同的模型,它们共享许多相同的属性。因此,在每个模型中,我必须指定相同的属性,然后指定特定于特定模型的属性

有没有什么方法可以创建一些列出这些基本属性的类,然后从该类继承而不使用单表继承?因为如果我将所有共享属性和Mongoid包含放在一个模型中,并从其他模型中的基础模型继承,那么STI将被强制执行,并且我的所有模型都存储在一个mongodb集合中,由“_type”字段区分

这就是我所拥有的:

class Model_1
  include Mongoid::Document

  field :uuid, :type => String
  field :process_date, :type => String
  ...
end

class Model_2
  include Mongoid::Document

  field :uuid, :type => String
  field :process_date, :type => String
  ...
end
但这就是我想要的功能:

class Base_model
  field :uuid, :type => String
  field :process_date, :type => String
end

class Model_1 < Base_model
  # To ensure STI is not enforced
  include Mongoid::Document

  # Attribute list inherited from Base_model
end
class-Base\u模型
字段:uuid,:type=>String
字段:进程\日期,:type=>String
结束
类模型\u 1<基本\u模型
#确保不强制执行STI
include Mongoid::Document
#从基本模型继承的属性列表
结束
问题是,如果基本模型中没有“include Mongoid::Document”,那么该基本模型就不知道“field…”功能。但是,如果将mongoid include放入基础模型并从中继承,则STI将被强制执行


我不能针对这种特殊情况进行STI,但拥有多个模型,并且一遍又一遍地指定相同的属性列表,这是一个编码噩梦(越来越多的模型,每个模型共享大约15-20个属性,所以任何时候我都必须更改模型名称,在任何地方都要更改它,这是一个很大的努力…).

您可以在模块中定义公共属性并将其包括在内

require 'mongoid'

module DefaultAttrs

  def self.included(klass)
    klass.instance_eval do
      field :uuid, :type => String
    end
  end

end

class Foo
  include Mongoid::Document
  include DefaultAttrs

  field :a, :type => String
end

class Bar
  include Mongoid::Document
  include DefaultAttrs

  field :b, :type => String
end

我有完全相同的问题,最初想采用mixin方法。然而,在与一些专家讨论之后,发现使用mongoids单表继承(所有子元素的一个集合)可能是一种方法,这取决于您的用例。请看我的帖子:

您可以将它们捆绑到一个新模块中,即

module Mongoid
  module Sunshine
    extend ActiveSupport::Concern

    included do
      include Mongoid::Document
      include Mongoid::Timestamps
      include Mongoid::TouchParentsRecursively
      include Mongoid::Paranoia
      include Mongoid::UUIDGenerator
    end
  end
end


class School
  include Mongoid::Sunshine
end

那很酷;这正是我要找的。模块是否被视为模型?将模块放在app/models文件夹中是标准做法,还是通常放在/lib文件夹中?我从来没有真正需要使用模块或进行类似的元编程,但这正是我想要的答案。模块只是容器。它们类似于类,但无法实例化,因此在Ruby编程语言中,它们经常被用作混合插件。lib文件夹是一个很好的存放它的地方。