1. Kondisi saat membuat record baru dengan model.save
before_validation --> before_validation_on_create --> after_validation --> after_validation_on_create --> before_save --> before_create --> Melakukan Operasi Insert ke Database --> after_create --> after_save
2. Kondisi saat melakukan update record dengan model.save
before_validation --> before_validation_on_update --> after_validation --> after_validation_on_update --> before_save --> before_update --> Melakukan Operasi Update ke Database --> after_update --> after_save
3. Kondisi saat menghapus record dengan model.destroy
before_destroy --> Melakukan Operasi Delete Ke Database --> after_destroy
Total callback diatas adalah delapan belas, dua callback yang tersisa adalah after_find dan after_initialize. Perlu diingat, harap hati-hati saat menggunakan callback after_find dan after_initialize karena akan mempengaruhi perfomansi. Hal ini disebabkan saat melakukan operasi database select dapat menghasilkan banyak sekali record dan kedua callback tersebut akan dipanggil sebanyak record yang ada.
Contoh Penggunaan Callback
Berikut ini adalah contoh bagaimana menggunakan callback.
class Post < ActiveRecord::Base
before_save :compile_bb
def compile_bb
self.body = self.body_bb.bbcode_to_html if self.body_bb
end
end
0 comments:
Post a Comment