Rails 7 adds change tracking methods for belongs_to associations
Sometimes minor updates add the most joy to users! A recent Rails update introduced the ability to monitor for changes in belongs_to associations. This brings in a welcome change for developers who like to conform to “the Rails way”.
Now, let’s try to do the same thing when a posts’ category changes.
This is an eyesore! We have an association called category, but we can’t monitor for its change. Rather, we have to resort to a rather crude way of monitoring for category_id changes. This isn’t very “the Rails way”.
Fortunately, Rails 7 now introduces a way to do this. With this PR, we can now do this.
association_changed? method (assuming an association named
true if a different associated object has been assigned and, the foreign key will be updated in the next save!
We also get access to this method,
association_previously_changed? which returns
true if the previous save updated the association to reference a different associated object.
post.category # => #<Post category_id: 123, title: "Welcome to Rails!">