ActiveSupport :: Concern Callback - NilClass的未定义方法

时间:2016-07-26 17:11:46

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

我正在尝试设置一个实用程序回调,可以使用ActiveSupport::Concern在我的Rails应用程序中用于多个模型。我有以下Postable模块:

/app/models/concerns/postable.rb

module Concerns::Postable
    extend ActiveSupport::Concern

    included do |base|
        base.after_save :correct_article_url, if: Proc.new { |post| post.article_url.present? }
    end

    def correct_article_url
        # do something with the url
    end
end

这是我的Post模型:

/app/models/post.rb

class Post < ActiveRecord::Base
    include Concerns::Postable
end

当我创建Post的新实例并调用post.save时,我收到以下错误:

NoMethodError - undefined method `correct_article_url' for #<Post:0x007fdb58a35b98>

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

我认为这应该解决它(也检查你的方法名称的拼写)

module Concerns::Postable
    extend ActiveSupport::Concern

    included do
        after_save :correct_article_url, if: Proc.new { |post| post.article_url.present? }
    end

    def correct_article_url
        # do something with the url
    end
end

答案 1 :(得分:0)

为什么使用命名空间?只需从模块和包含中删除名称空间,它就可以正常工作

 module Postable
   extend ActiveSupport::Concern

   included do |base|
      base.after_save :correct_article_url, if: Proc.new { |post| post.article_url.present? }
 end

 def correct_article_url
     # do something with the url
 end
end