Wednesday, November 16, 2011

How to set and skip callback with rails

Rubies,
     Want to set and skip the callback dynamically? Here is the some method which we can use to get required output.

For rails 3

Active Support provides the methods call 'skip_callback'  and 'set_callback'.
Lets we see the usage of those methods.

Assume in model we have after_save callback called 'process_me'. Now we have to skip the callback during the execution of certain method and than reset back.

# skip the callback
ModelName.skip_callback(:save, :after, :process_me)

# set the callback
ModelName.set_callback(:save, :after, :process_me)

For rails 2 

Active Record provides the some built in methods to restrict callback.

model_object.send(:update_without_callbacks) - restrict callback during update method's invocation
model_object.send(:create_without_callbacks) - restrict callback during create
method's invocation
model_object.send(:create_or_update_without_callbacks) - restrict callback during create/update method's invocation

No comments:

Post a Comment