2

我正在尝试创建一个包含与 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

这是不可能的,还是我做错了什么?

4

1 回答 1

2

我认为模块中的关联( from Scalableto Scale)很好,但是 from Scaleto的另一半Scalable是个问题。Scalable那是因为当你真的需要它来引用类时,目标类是从将 Mongoid 引导到模块的关联名称派生的ScalableModel。然后引发错误,因为 Mongoid 将模块视为模型类。

起初我认为您必须在 Scalable 包含块中定义关联的两侧,但事实证明您可以通过将关联标记为多态来修复关联的 Scale 侧。

还有另一个问题,self.scale.create引发异常,因为在保存其父对象之前无法创建新的子对象。为了解决我刚刚使用after_save的 . 这就是我想出的:

module Scalable
  extend ActiveSupport::Concern

  included do
    references_many :scales, :as => :scalable
    after_save :add_scale                     # changed from before_save
  end

  module InstanceMethods
    def add_scale
      self.scales.create
    end
  end
end

class Scale
  include Mongoid::Document
  referenced_in :scalable_model, :index => true, :polymorphic => true
end

class ScalableModel1
  include Mongoid::Document
  include Scalable
end

class ScalableModel2
  include Mongoid::Document
  include Scalable
end

s1 = ScalableModel1.create
s2 = ScalableModel2.create
于 2011-07-28T12:10:11.763 回答