一次将关联回调附加到给定模型的所有关联

时间:2020-02-11 00:55:06

标签: ruby-on-rails rails-activerecord

假设存在一个与用户表相关的具有多个关联的Account模型,例如:

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

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

1 个答案:

答案 0 :(得分:2)

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

它也是不需要的,因为您可以通过装饰方法来实现相同的目的:

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