2
我正嘗試創建一個包含與Mongoid的多態關係的模塊。簡單的例子:ActiveSupport中的Mongoid關係::關注模塊
module Scalable
extend ActiveSupport::Concern
included do
references_many :scales, :as => :scalable
before_save :add_scale
end
module InstanceMethods
def add_scale
self.scales.create
end
end
end
class Scale
include Mongoid::Document
referenced_in :scalable, :index => true
end
class ScalableModel
include Mongoid::Document
include Scalable
end
然而,當我試圖像ScalableModel.create
運行的東西,我得到以下錯誤:
NoMethodError Exception: undefined method `relations' for Scalable:Module
這是不可能的,還是我做錯了什麼?
非常感謝Steve,這很好地工作。通過添加':autosave => true'並將'self.scales.create'更改爲'self.scales.build'在回調中,我實際上能夠保留回調。 – geetarista