我有以下型号。
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'}]
假设我要更新Company 1用户,我将执行以下操作:
Company.first.update :users => [User.first, User.second]
这将按预期运行,并在CompanyUser
模型上创建2条新记录。
但是如果我想再次更新怎么办?像运行以下命令:
Company.first.update :users => [User.third, User.fourth]
这将销毁前2条记录,并在CompanyUser
模型上创建另外2条记录。
从技术上来说,我是[[0]更新过] Company
模型,所以如何在after_update
模型上使用Company
方法检测这些变化?但是,更新属性可以正常工作:
Company.first.update :name => 'New Company Name'
我如何也可以在关联上使用它?
到目前为止,我已经尝试了以下方法,但无济于事:
attr_accessor
,并检查其是否更改。