【发布时间】:2020-04-12 21:48:23
【问题描述】:
我有以下型号。
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 模型,那么我如何在Company 模型上使用after_update 方法检测这些变化?
但是,更新属性就可以了:
Company.first.update :name => 'New Company Name'
我怎样才能让它也适用于关联?
到目前为止,我尝试了以下方法,但无济于事:
【问题讨论】:
标签: ruby-on-rails activerecord rails-activerecord has-many-through ruby-on-rails-6