ActiveSupport :: Concern ClassMethod未附加到主机类

时间:2015-08-22 23:36:11

标签: ruby-on-rails ruby ruby-on-rails-4

我在models/concerns/sluggable.rb

中有这个
module Sluggable
    extend ActiveSupport::Concern

    module ClassMethods
        def sluggify(str, type)
            # ...
        end     
    end
end

我已将其纳入models/slug.rb:

class Slug < ActiveRecord::Base
    include Sluggable
    # ...
    before_save :create_slug

    private
        def create_slug
            self.slug = Slug.sluggify(self.title, 'item')
        end
end

我认为模块中的sluggify方法现在可以作为Slug的类方法使用,但似乎并非如此。尝试将模型插入数据库时​​出现undefined method: sluggify错误。

可以从Rails控制台获得Sluggable模块。我可以确认我的代码是正确的:

module Sluggable
    def sluggify(str, type)
        # ...
    end
end

class SluggableTest
    extend Sluggable
end

slug = SluggableTest.sluggify('string to sluggify', 'item')

那么为什么我不能让它在模型中作为一个关注点工作?

2 个答案:

答案 0 :(得分:0)

尝试在include Sluggable类的顶部添加Slug,如下所示:

  class Slug < ActiveRecord::Base
    include Sluggable
    # ...
    before_save :create_slug

    private

    def create_slug
      self.slug = Slug.sluggify(self.title, 'item')
    end
  end

因为,你是对的。一旦sluggify Sluginclude模块中的Sluggable模块将Slug类附加Slug方法,该方法将作为include Sluggable类的方法提供{1}}课程。我想,因为您的Slug类之上没有sluggify,所以Sluggable方法在Slug模块包含在{{1}之前被调用}}因此它得到了undefined method错误,这是有道理的!

答案 1 :(得分:0)

您在嵌套模块中定义方法,但不包含或扩展它。以下是正确的模板:

false