Use Callbacks to Manipulate an ActiveRecord Object's has_many Associates

Say you have an ActiveRecord that has many categories:

class Article < ActiveRecord::Base
    has_many :categories
end

If you want to load the categories when the article is initialized, or if you want to save the categories when the article is saved, don't try to override "initliaze" or "save" methods. Use the callback functions in ActiveRecord::Callbacks.

class Article < ActiveRecord::Base
    has_many :categories
 
    def after_initialize
        categories
    end
 
    def after_save
        categories.each do |category|
            category.save
        end
    end
end

This works as long as you don't care to pass in additional parameters to the initializer or save action.