【问题标题】:Attach an association callback to all associations for a given model at once一次将关联回调附加到给定模型的所有关联
【发布时间】:2020-02-11 00:55:06
【问题描述】:

假设有一个 Account 模型,其中包含与 User 表相关的多个关联,例如:

class Account < ActiveRecord
  has_many :users
  has_many :clients, ..., :source => :user
  has_many :managers, ..., :source => :user
end

如果我将.delete() 与其中任何一种关联一起使用,它将删除帐户与用户之间的现有关系。当这种关系被删除时,我想注册一个回调。我可以在每个 has_many 声明中附加:before_remove =&gt; :callback,但我想知道是否有任何快捷方式可以自动将回调添加到源设置为:user 的每个现有关联。

【问题讨论】:

  • 您是否尝试将回调添加到has_many :users 并检查它是否适用于所有人?
  • @FeifeiXiong 是的,我试过了 - 不起作用

标签: ruby-on-rails rails-activerecord


【解决方案1】:

没有。没有这样的选择。可能是因为它不是一个好主意,因为它确实会增加复杂性并导致大量不良副作用。

而且它也不需要,因为你可以通过装饰方法来实现同样的事情:

module MyApp
  module Assocations

    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def decorate_association(**options, &block)
         yield AssocationDecorator.new(self, options)
      end
    end

    class AssocationDecorator
      attr_accessor :options, :klass
      def initialize(klass, **options)
        @klass = klass
        @options = options
      end
      def has_many(name, scope = nil, **options, &extension)
        @klass.has_many(name, scope, options.reverse_merge(@options), &extension)
      end
    end
  end
end
class Account < ActiveRecord
  include MyApp::Assocations
  decorate_association(before_remove: :callback, source: :user) do |decorator|
    decorator.has_many :clients
  end
end

【讨论】:

  • 谢谢,我最终做了类似的事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2016-10-22
  • 2014-03-25
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多