ruby-on-rails - 一次将关联回调附加到给定模型的所有关联
问题描述
假设有一个 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
。
解决方案
不,没有这样的选择。可能是因为它不是一个好主意,因为它确实会增加复杂性并导致大量不良副作用。
而且它也不需要,因为您可以通过装饰方法来实现相同的目标:
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
推荐阅读
- django - 将 prefetch_related() 添加到 Django 身份验证后端
- c - 在 C 中返回调和平均值和平均值的函数
- java - 如何为 vscode 终端定义命令/变量?
- lua - 我的 Lua 脚本中的错误:尝试将布尔值与数字进行比较
- python - Python 中的 Google Cloud API 输出格式
- uno-platform - “页面”类型不支持直接内容
- r - 缩短 ggplot2 dodge_position 中的条形图
- c# - 解析作为对象传递给 C# UDF 的数组以用于 Azure 流分析
- r - r 函数根据来自不同数据帧的日期/值计算新变量
- php - 为什么我的会话在数据刷新后被取消?