-->

有没有办法共享属性规格,而无需使用单表继承 - 通过mongoid适配器使用MongoDB的Rail

2019-09-16 18:12发布

可能是一个令人困惑的标题,但不知道怎么回事,把它。 例如应使其更清晰。 我有很多共同的属性的许多不同的模式。 因此,在每个模型我必须指定这些相同的属性,然后是特定于特定模型的属性。

有没有什么办法可以创建一些类,列出了这些基本属性,然后从该类继承,而无需使用单表继承? 因为如果我把所有的共享属性和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

问题是,如果你没有在Base_model该“包括Mongoid ::文档”,然后是基本型号不知道“田......”的功能。 但是,如果你把mongoid包括在基本模型,并继承它,STI强制执行。

我不能为这种特殊的情况做STI但它是一个编码的噩梦有多个型号,全部采用指定的一遍又一遍相同的属性列表(也有越来越多的车型和15-20属性每股,所以我随时要改变这是一个很大的努力来改变它无处不在,...)的型号名称。

Answer 1:

您可以定义一个模块中的公共属性和包括。

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


Answer 2:

我有相同的问题,最初想要去的混入方法。 然而,说起一些专家事实证明,使用mongoids单表继承(一个集合的所有子元素)可能是要走的路后,这取决于你的使用情况。 请在这里看到我的帖子: 单个集合与用于继承的对象单独集合



Answer 3:

你可以捆绑他们进入一个新的模块,即

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


文章来源: Rails 3 using MongoDB via mongoid adapter - is there any way to share attribute specifications without using Single-Table Inheritance?