ruby-on-rails - 如何通过关联检测has_many的变化?
问题描述
我有以下型号。
class Company < ApplicationRecord
has_many :company_users
has_many :users, :through => :company_users
after_update :do_something
private
def do_something
# check if users of the company have been updated here
end
end
class User < ApplicationRecord
has_many :company_users
has_many :companies, :through => :company_users
end
class CompanyUser < ApplicationRecord
belongs_to :company
belongs_to :user
end
然后我有这些种子:
Company.create :name => 'Company 1'
User.create [{:name => 'User1'}, {:name => 'User2'}, {:name => 'User3'}, {:name => 'User4'}]
假设我要更新公司 1 的用户,我将执行以下操作:
Company.first.update :users => [User.first, User.second]
这将按预期运行,并将在CompanyUser
模型上创建 2 条新记录。
但是如果我想再次更新呢?就像运行以下命令:
Company.first.update :users => [User.third, User.fourth]
这将销毁前 2 条记录,并在CompanyUser
模型上创建另外 2 条记录。
问题是我已经在技术上“更新”了Company
模型,那么如何使用模型after_update
上的方法检测这些变化Company
?
但是,更新属性就可以了:
Company.first.update :name => 'New Company Name'
我怎样才能让它也适用于关联?
到目前为止,我尝试了以下但无济于事:
解决方案
has_many 关系上有一个集合回调 before_add、after_add。
class Project
has_many :developers, after_add: :evaluate_velocity
def evaluate_velocity(developer)
#non persisted developer
...
end
end
推荐阅读
- php - php equivalent to Twig's "ignore missing" in include statement
- c# - New XML file from another large XML file, problem with namespaces
- r - Append latest values to older records
- git - Limit remote branch decorations but keep HEAD decoration
- c# - 有没有办法为类名声明变量类型?
- python - Using gcsfs to download csv - how to convert from byte to string?
- java - Android 使用 ImageView 按钮打开导航抽屉
- angular - 获取用户从 ngFor 列表中选择的值
- node.js - 我想发出一个命令,让机器人可以记录编辑过的消息
- python - 我从音频文件中提取 mfccs 功能并指定 numcep = 13 但它超过 13 列,为什么?