【问题标题】:Monkey patching and callback error猴子修补和回调错误
【发布时间】:2015-05-29 09:25:15
【问题描述】:

我在 Rails 4 应用程序中使用了两个 gem:acts_as_tenantsimple_hashtags

如果一个租户上存在主题标签,则不会为另一个租户重新保存它。所以我想覆盖 find_or_create_by_name 和 find_by_name 方法。
为此,我还需要覆盖parsed_hashtags method,但为了让我的应用程序使用它,我还需要包含回调

before_save :update_hashtags

我有一个initializer,我第一次使用它来将多租户系统用于标签(因此会自动保存tenant_id)。我添加了方法,但是在尝试覆盖回调时,我碰壁了。

如果我在要点中使用扩展 ActiveSupport::Concern,我会收到此错误并且无法启动我的应用程序。

lib/active_support/concern.rb:126:in `included': Cannot define multiple 'included' blocks for a Concern (ActiveSupport::Concern::MultipleIncludedBlocks)
        from /Users/schatteleyn/subarashi/config/initializers/hashtags.rb:16:in `<module:Hashtaggable>'
        from /Users/schatteleyn/subarashi/config/initializers/hashtags.rb:14:in `<module:SimpleHashtag>'
        from /Users/schatteleyn/subarashi/config/initializers/hashtags.rb:1:in `<top (required)>'

如果我使用带有

的版本
def self.included(base)
  base.class_eval do
    before_save :do_something
  end
end

我收到此错误,可以启动我的应用程序,但在任何页面上都收到此错误。

undefined method `before_save' for HashtagConcern:Module

我很茫然,这是我能找到的仅有的两个解决方案,而且我似乎无法让它们发挥作用。 有没有其他方法可以在模块中使用回调?或者也许是另一种解决按名称和租户查找问题的方法?

【问题讨论】:

    标签: ruby-on-rails monkeypatching


    【解决方案1】:

    为了让 simple_hashtag 能够识别租户,只需覆盖 Hashtag 模型的验证,例如:

    SimpleHashtag::Hashtag.clear_validators!
    module SimpleHashtag
      class Hashtag < ActiveRecord::Base
        acts_as_tenant :tenant
        validates :name, :uniqueness => { :scope => :tenant }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 2013-12-26
      • 2012-06-14
      • 2012-03-29
      • 2016-10-30
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多