Introducing the Dirty Associations Plugin
Rails has this handy feature called dirty objects, which allows you to easily see how a record has changed during its lifetime. You get several handy methods on each ActiveRecord object:
task = Task.first task.changed? # => false task.name = "My New Name" task.changed? # => true task.name_was # => "The Original Name"
And so forth.
The new Dirty Associations plugin allows you to track changes made to your model’s associations using an interface similar to the original dirty object behavior.
Say we have an ActiveRecord class:
class Task < ActiveRecord::Base belongs_to :user has_many :todos has_many :comments keep_track_of :user, :todos # enable dirty methods for these associations only end
Now you can enable the dirty association methods merely by calling enable_dirty_associations on an instantiated object:
task = Task.first task.enable_dirty_associations do task.user = User.last # replace the user association task.associations_changed? # => true task.user_changed? # => true task.user_was # => ...original user object... task.user_id_was # => 3 task.todos.create(:name => "New Todo") # build and create a new has_many association task.todos_changed? # => true task.todos_added? # => true task.todos_removed? # => false task.todos_were # => ...collection of todos objects at the start of tracking... task.todo_ids_were # => [370,39,298] end
You can install this plugin into your Rails application with the following command:
script/plugin install git://github.com/daphonz/dirty_associations.git
Comments, questions, and (especially) bug reports are highly valued. You can use the GitHub page for Dirty Associations to pass these along, and also read more documentation, examples, etc.
Originally posted by Casey Dreier
