10

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

François Beausoleil
  • 16,265
  • 11
  • 67
  • 90
  • I suppose it would depend on whether Rails caches associations when you query them for an object – wolfson Apr 02 '18 at 02:44
  • I may be not understanding the question correctly, but shouldn't calling `#name_changed?` on the association work as well? – user2490003 Apr 02 '18 at 03:55
  • @user2490003, I don't want to know if the name of an attribute in one of the records changed, I want to know if any records were added or removed from the association. – François Beausoleil Apr 03 '18 at 03:37

3 Answers3

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

Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
0

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

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

smile2day
  • 1,585
  • 1
  • 24
  • 34
0

has_many - nope but if we talk about belongs_to :user you can use something like this object.saved_change_to_user_id?

  • `object.saved_change_to_user_id?` == `object.user_id_changed?`, so it only returns true in case object change user, however, i think this question about tracking whether the user belongs to object is changed or not (such as change user name). – Lam Phan Sep 17 '21 at 03:15