首页 > 解决方案 > 如何通过关联检测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'

我怎样才能让它也适用于关联?

到目前为止,我尝试了以下但无济于事:

标签: ruby-on-railsactiverecordrails-activerecordhas-many-throughruby-on-rails-6

解决方案


has_many 关系上有一个集合回调 before_add、after_add。

class Project
  has_many :developers, after_add: :evaluate_velocity

  def evaluate_velocity(developer)
    #non persisted developer
    ...
  end
end

更多详情:https ://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Association+callbacks


推荐阅读