Prev | Current Page 174 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

destroy,
ActiveRecord::Base.destroy_all, ActiveRecord::Base.delete, or
ActiveRecord::Base.delete_all statement is executed.
class Account < ActiveRecord::Base
def before_destroy
Contacts.delete_all(["Account_ID = ?", self.Account_ID])
end
end
With this example, we are making sure that we delete all contact records that were associated
with an account record before we delete the actual account record. This would produce
similar results to performing a cascading delete within a database.
after_destroy
This method is executed after an ActiveRecord::Base.destroy, ActiveRecord::Base.destroy_
all, ActiveRecord::Base.delete, or ActiveRecord::Base.delete_all statement is executed.
CHAPTER 4 ?–  CORE FEATURES OF ACTIVE RECORD 68
class Account < ActiveRecord::Base
def after_destroy
logger.info("Account record was deleted")
end
end
This example assumes that we have a logger object to which we are recording certain actions;
we are logging the fact that an account record was deleted from the database.
One Down,Two to Go
You should now be an expert on Active Record callbacks, or at least well on your way.


Pages:
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186