【问题标题】:Mixin to define model associations in Rails 3.1Mixin 在 Rails 3.1 中定义模型关联
【发布时间】:2012-01-04 10:14:16
【问题描述】:

我有一系列不同的模型,每个模型都与属性模型共享多态关联。我正在尝试编写一个 mixin 来稍微干燥代码,但是它们不起作用,请您提供一些调试帮助。我的 mixin 看起来像这样......

module ModelWithProperties
    def self.included?(base)
        base.class_eval do
            has_many :properties, :as=>:parent
        end
    end

    def examplesharedfunction
        /// stuff here
    end
end

然后我的模型看起来像这样......

class Myobjects < ActiveRecord::Base
    include ModelWithProperties
end

但是,当我运行所有这些时,关联似乎已经采取('undefined method 'properies' for #can access the examplesharedfunction.

有什么线索/提示吗?

【问题讨论】:

    标签: ruby-on-rails models mixins


    【解决方案1】:

    包含模块时调用的钩子是self.included 而不是self.included?

    你也可以使用ActiveSupport::Concern

    module M
      extend ActiveSupport::Concern
    
      included do
        has_many :properties, :as=>:parent
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多