使用Rails Concerns的未定义类方法

时间:2016-01-13 16:18:35

标签: ruby-on-rails ruby

我完成了所有内容,如下所述:question

但我一直收到错误:

NoMethodError: undefined method `parent_model' for Stream (call 'Stream.connection' to establish a connection):Class

在模型/关注faculty_block.rb

module FacultyBlock
  extend ActiveSupport::Concern
  included do
    def find_faculty
      resource = self
      until resource.respond_to?(:faculty)
        resource = resource.parent
      end
   resource.faculty
    end
    def parent
      self.send(self.class.parent)
    end
  end

  module ClassMethods
    def parent_model(model)
      @@parent = model
    end
  end

end

[Program, Stream, Course, Department, Teacher].each do |model|
  model.send(:include, FacultyBlock)
  model.send(:extend, FacultyBlock::ClassMethods) # I added this just to try
end

在初始化程序中:

require "faculty_block"

方法调用:

class Stream < ActiveRecord::Base
 parent_model :program
end

1 个答案:

答案 0 :(得分:0)

似乎在加载问题之前已加载Stream,请确保已在类定义中应用了关注点。当rails loader与Stream常量的类名匹配时,它会在faculty_block的完成评估之前自动加载它,因此用符号替换其中的常量:

[:Program, :Stream, :Course, :Department, :Teacher].each do |sym|
   model = sym.to_s.constantize
   model.send(:include, FacultyBlock)
   model.send(:extend, FacultyBlock::ClassMethods) # I added this just to try
end