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

浪子不回头ぞ 提交于 2019-12-05 19:17:55

You can define the common attributes in a module and include that.

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
Boenne

I had the exact same question and wanted to go for the mixin approach initially. However, after talking to some experts it turns out that using mongoids single table inheritance (one collection for all child elements) may be the way to go, depending on your use case. Please see my post here: single collection vs. separate collections for inherited objects

You can bundle them into a new module, i.e.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!