Ruby on rails 带Mongoid的Rails模块

Ruby on rails 带Mongoid的Rails模块,ruby-on-rails,ruby,mongodb,mongoid,Ruby On Rails,Ruby,Mongodb,Mongoid,我试图将一些模型类扩展为“资产”类。 这四种类型的资产中的每一种都能够生成一个set\u回调(:save,:before)因此,我希望它们扩展一个具有set\u回调的资产类(以及其他方法),而不是编写四个相同的方法 起初,我只是尝试让他们扩展Asset类,但遇到了一些问题,当我将其中一个资产保存到数据库(mongo)时,他们插入的集合被称为Asset,而不是他们自己的名称 在我用谷歌搜索了一下之后,人们似乎建议改用模块。所以我试过: module Asset field :slug, :ty

我试图将一些模型类扩展为“资产”类。 这四种类型的资产中的每一种都能够生成一个
set\u回调(:save,:before)
因此,我希望它们扩展一个具有set\u回调的资产类(以及其他方法),而不是编写四个相同的方法

起初,我只是尝试让他们扩展Asset类,但遇到了一些问题,当我将其中一个资产保存到数据库(mongo)时,他们插入的集合被称为Asset,而不是他们自己的名称

在我用谷歌搜索了一下之后,人们似乎建议改用模块。所以我试过:

module Asset
  field :slug, :type => String

  set_callback(:save, :before) do |document|
    # make document.slug = to whatever
  end
end

class Video
  include Mongoid::Document
  include Asset
  field :video_name, :type => String
  field :description, :type => String
  field :some_more_fields, :type => String
end
但当我包含资产时,会出现一些错误:

'undefined method `field' for Asset:Module'

注意:我使用的是Mongoid,方法字段在资产模块的上下文中是未知的。因此,仅当包含模块时,才需要调用字段:

  module Asset
    def self.included(base)
      base.send(:field, :slug, :type => String)
    end
  end

编辑:将代码包装在代码块中

好的,使用关注点可以使编写更简单、更好:

module Asset
 include extend ActiveSupport::Concern
  included do
   field: slug, type: String
   before_create: :notify_on_create
   scope: my_scope, ->(var) { where(slug: var) }
  end
 end
end

有关更多详细信息,请参阅。

谢谢,这对我很有用。还使用了
base.send(:在创建之前,:在创建时通知)
base.send(:嵌入多个,:通知,:as=>:可通知)
在我的可通知模块中。您如何发送以声明该模块中的范围?我得到
包含:资产:模块(NoMethodError)`的未定义方法
字段。也许这在Ruby 2.3.1上不起作用?