Ruby on rails 如何通过关联检测has\u MUN中的变化?
我有以下几种型号Ruby on rails 如何通过关联检测has\u MUN中的变化?,ruby-on-rails,activerecord,rails-activerecord,has-many-through,ruby-on-rails-6,Ruby On Rails,Activerecord,Rails Activerecord,Has Many Through,Ruby On Rails 6,我有以下几种型号 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 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 1用户,我将执行以下操作:
Company.first.update :users => [User.first, User.second]
Company.first.update :users => [User.third, User.fourth]
这将按预期运行,并将在CompanyUser
model上创建2条新记录
但是如果我想再次更新呢?如运行以下命令:
Company.first.update :users => [User.first, User.second]
Company.first.update :users => [User.third, User.fourth]
这将销毁前2条记录,并在CompanyUser
model上创建另外2条记录
问题是我已经在技术上对公司
模型进行了更新,那么如何在公司
模型上使用更新后的方法来检测这些变化呢
但是,更新属性效果很好:
Company.first.update :name => 'New Company Name'
我怎样才能使它也适用于协会
到目前为止,我尝试了以下方法,但没有效果:
我感觉你问错了问题,因为如果不破坏当前的关联,就无法更新关联。正如你所说:
这将销毁前2条记录,并在CompanyUser机型上创建另外2条记录。
知道我将建议您尝试以下代码:
Company.first.users您可以为此使用attr\u访问器
,并检查它是否更改
class Company < ApplicationRecord
attr_accessor :user_ids_attribute
has_many :company_users
has_many :users, through: :company_users
after_initialize :assign_attribute
after_update :check_users
private
def assign_attribute
self.user_ids_attribute = user_ids
end
def check_users
old_value = user_ids_attribute
assign_attribute
puts 'Association was changed' unless old_value == user_ids_attribute
end
end
class公司
现在,在关联更改后,您将在控制台中看到消息
您可以将
放置
更改为任何其他方法。在添加前、添加后有一个集合回调
class Project
has_many :developers, after_add: :evaluate_velocity
def evaluate_velocity(developer)
#non persisted developer
...
end
end
有关更多详细信息:不幸地将其命名为Company.first.update(用户:[User.first,User.second])