如何确定关联是否在ActiveRecord中更改? [英] How to determine if association changed in ActiveRecord?
问题描述
ActiveRecord提供更改跟踪,其中调用 #name_changed?
返回true / false取决于 name
属性是否更改在加载模型的时间到现在之间。
ActiveRecord offers change tracking, where calling #name_changed?
returns true/false depending on whether the name
attribute changed between when the model was loaded and now.
关联是否等效?我专门在寻找has_many关联,但是所有关联类型都会有用。
Is there an equivalent for associations? I am specifically looking for has_many associations, but all association types would be useful.
Rails 5.2,Ruby 2.5.1
Rails 5.2, Ruby 2.5.1
推荐答案
好,不是一个答案,但这是我想出的解决方法。
Ok, not a answer but this is a workaround I came up with.
在我的项目中我已经在使用宝石 已审核
以跟踪更改我也想接收更改的模型。在我的情况下,模型是 Location
,而我要检查位置是否已更改的模型是 Employee
In my project I was already using the gem audited
to keep track of changes on the model I also want to receive changes on. In my case the model is Location
and the model I want to check if the location was changes is Employee
然后在 after_save
中检查是否对该位置进行了审核,以及是否在几秒钟内创建了该审核。如果是这样,我能够检查更改。
In the after_save
I then check if there is made an audit on the location and if it's created within seconds. If so, I'm able to check the changes.
简化的示例:
# app/models/location.rb
class Location < ApplicationRecord
audited
end
# app/models/employee.rb
class Employee < ApplicationRecord
after_save :inform_about_changes!
belongs_to :location
def inform_about_changes!
last_location_change = location.audits.last
if last_location_change.created_at.between?(2.seconds.ago, Time.now)
if last_location_change.audited_changes.include? 'city'
city_was = last_location_change.audited_changes[0]
end
end
end
end
再一次,这不是一个答案,但是在我的情况下确实可以解决问题
Once again, this is not an answer, but it did the job in my case
这篇关于如何确定关联是否在ActiveRecord中更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!