【问题标题】:Callbacks aren't working in model decorator Rails 5 Spree 4回调在模型装饰器 Rails 5 Spree 4 中不起作用
【发布时间】:2020-03-27 07:34:00
【问题描述】:

我是 Rails 5/Spree 4 的新手,但我无法让回调在我的模型中工作。我想在 Spree 中创建产品后运行一些方法,但我不明白 included do 这对我来说是全新的东西。

型号:app/models/spree/product_decorator.rb

require 'active_support/concern'

module Spree
  module ProductDecorator
    extend ActiveSupport::Concern

    included do
        after_create :assign_prototype
    end

    def assign_prototype
        binding.pry
    end

  end
end

我假设我忽略了一些愚蠢的事情,但我已经搞砸了一个小时。为什么这里不能识别after_create 方法?

【问题讨论】:

  • 你有没有像include Spree::ProductDecorator 一样把这个模块加入到模型中

标签: ruby-on-rails spree


【解决方案1】:

这是给定in the docs的实际示例:

module MyStore
  module Spree
    module ProductDecorator
      def some_method
        ...
      end
    end
  end
end

::Spree::Product.prepend MyStore::Spree::ProductDecorator

如您所见,如果您不在模块中包含/预先添加 ::Spree::Product,则实际上不会发生任何事情。而且你还应该把你的代码放在你自己的模块中,这样你就不会破坏现有的Spree::ProductDecorator

included do
  # ...
end

与Spree无关。全部是 ActiveSupport::Concern 并包装了这个常见的 Ruby 习语:

module Spree
  module ProductDecorator
    def self.included(base)
      base.class_eval do
        after_create :assign_prototype
      end
    end

    def assign_prototype
      binding.pry
    end
  end
end

Module#included 是 Ruby 中内置的一个钩子,当模块包含在类中时,它允许您在类的上下文中执行代码。这就是你如何在模块 mixin 的模型类主体中执行访问器、验证、回调等或任何其他操作。

【讨论】:

    猜你喜欢
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多