【问题标题】:Mongoid Relationship within an ActiveSupport::Concern ModuleActiveSupport::Concern 模块中的 Mongoid 关系
【发布时间】:2011-07-27 23:33:10
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails-3 mongoid relationship ruby-1.9.2


    【解决方案1】:

    我认为模块中的关联(从ScalableScale)很好,但是从ScaleScalable 的另一半是个问题。那是因为目标类是从将 Mongoid 引导到 Scalable 模块的关联名称派生的,而您确实需要它来引用 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
    

    【讨论】:

    • 非常感谢史蒂夫,这非常有效。通过在回调中添加:autosave => true 并将self.scales.create 更改为self.scales.build,我实际上能够将回调保留为之前保存。
    猜你喜欢
    • 1970-01-01
    • 2012-01-30
    • 2011-09-05
    • 1970-01-01
    • 2012-09-14
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多