带有Mongoid的Rails模块

时间:2012-03-09 17:01:20

标签: ruby-on-rails ruby mongodb mongoid

我正在尝试将一些模型类扩展为“Asset”类。 四种类型的资产中的每一种都能够生成一个set_callback(:save, :before)的slug。因此,我不希望编写四个相同的方法,而是希望它们扩展一个具有set_callback的资产类(如以及其他方法)。

起初我试过让他们扩展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

2 个答案:

答案 0 :(得分:7)

在Asset模块的上下文中不知道method字段。因此,只有在包含模块时才需要调用字段:

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

编辑:代码块中的包装代码

答案 1 :(得分:2)

好的,使用关注点会使编写更容易,更好:

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

有关详细信息,请参阅http://api.rubyonrails.org/classes/ActiveSupport/Concern.html