1

我正在尝试设置一个实用程序回调,该回调可用于我的 Rails 应用程序中的多个模型,使用ActiveSupport::Concern. 我有以下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>

我在这里做错了什么?

4

2 回答 2

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
于 2016-07-26T17:53:31.283 回答
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
于 2016-07-26T19:15:07.657 回答