首页 > 解决方案 > 一次将关联回调附加到给定模型的所有关联

问题描述

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

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

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

标签: ruby-on-railsrails-activerecord

解决方案


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

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

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

推荐阅读