-->

How to determine if association changed in ActiveR

2020-08-22 13:30发布

问题:

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.

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

回答1:

Ok, not a answer but this is a workaround I came up with.

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

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.

Simplified example:

# 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



回答2:

there is no #association_changed? equivalent on associations as far as the documention shows.

https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html