立即将关联回调附加到给定模型的所有关联
Attach an association callback to all associations for a given model at once
假设有一个帐户模型具有与用户相关的多个关联 table,例如:
class Account < ActiveRecord
has_many :users
has_many :clients, ..., :source => :user
has_many :managers, ..., :source => :user
end
如果我对这些关联中的任何一个使用 .delete()
,它将删除帐户与用户之间的现有关系。当这种关系被删除时,我想注册一个回调。我可以在每个 has_many 声明后附加 :before_remove => :callback
,但我想知道是否有任何快捷方式可以自动将回调添加到源设置为 :user
.[=14 的每个现有关联中=]
没有。没有这样的选择。可能是因为这不是一个好主意,因为它确实会增加复杂性并导致大量不良副作用。
也不需要它,因为您可以通过装饰方法来实现同样的目的:
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
假设有一个帐户模型具有与用户相关的多个关联 table,例如:
class Account < ActiveRecord
has_many :users
has_many :clients, ..., :source => :user
has_many :managers, ..., :source => :user
end
如果我对这些关联中的任何一个使用 .delete()
,它将删除帐户与用户之间的现有关系。当这种关系被删除时,我想注册一个回调。我可以在每个 has_many 声明后附加 :before_remove => :callback
,但我想知道是否有任何快捷方式可以自动将回调添加到源设置为 :user
.[=14 的每个现有关联中=]
没有。没有这样的选择。可能是因为这不是一个好主意,因为它确实会增加复杂性并导致大量不良副作用。
也不需要它,因为您可以通过装饰方法来实现同样的目的:
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