There are a few subtle differences to each approach,
so let??™s look a quick example to explain each.
Implementing Callbacks
The easiest way to implement a callback is to just overwrite the method within your model:
class Account < ActiveRecord::Base
def before_save
self.Account_Updated = Time.now
end
end
This approach works great for situations like the preceding example, where you want to
set values for fields programmatically or when you want each descendant of an inheritance
hierarchy to decide if it wants to call the super command and trigger the inherited callbacks??”
which points out the biggest disadvantage to the overwriting approach: your callbacks are not
executed through an inheritance hierarchy. This is probably most important, and obvious,
when using callbacks to delete associated records from other tables. Consider this example
from the Active Record documentation:
class Topic < ActiveRecord::Base
def before_destroy()
destroy_author
end
end
class Reply < Topic
def before_destroy()
destroy_readers
end
end
Basically, with this approach, when you delete a reply, the destroy_readers method is
called, but the destroy_author method is not.
Pages:
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172