Search code examples
ruby-on-railsrubymongoidactivesupport-concern

Multiple activesupport concerns in mongoid model


I'm not sure I understand how concerns work. I am trying to wrap up some common code into two modules that extend ActiveSupport::Concern, but when I include both, I get a error:

`included': Cannot define multiple 'included' blocks for a Concern (ActiveSupport::Concern::MultipleIncludedBlocks)

module AppCore
  class Student
    include Mongoid::Document
    include Mongoid::Timestamps
    include AppCore::Extensions::Models::TenantScoped
    include AppCore::Extensions::Models::UserScoped
  end
end

module AppCore::Extensions::Models
  module TenantScoped
    extend ActiveSupport::Concern
    included do
      field :tenant_id, type: Integer
      belongs_to :tenant, class_name: 'AppCore::Tenant'
      association_name = self.to_s.downcase.pluralize
      AppCore::Tenant.has_many association_name.to_sym, class_name: self.to_s
    end
  end
end

module AppCore::Extensions::Models
  module UserScoped
    extend ActiveSupport::Concern
    included do
      field :user_id, type: Integer
      belongs_to :user, class_name: 'AppCore::User'
    end
  end
end

Can I only include one Concern at a time? Should I move the two Scoped modules to tenant_scoped and user_scoped to ClassMethods and just make one model extension concern?


Solution

  • Your problem is that you most likely not follow the Rails auto loading conventions regarding folder/file naming that follows the module / class name structure.

    See Cannot define multiple 'included' blocks for a Concern (ActiveSupport::Concern::MultipleIncludedBlocks) with cache_classes = true for more info.