I'm using restful_authentication in my app. I'm creating a set of default users using a rake task, but every time I run the task an activation email is sent out because of the observer associated with my user model. I'm setting the activation fields when I create the users, so no activation is necessary.
Anyone know of an easy way to bypass observers while running a rake task so that no emails get sent out when I save the user?
Thanks.
Rails 3.1 finally comes with API for this: http://api.rubyonrails.org/v3.1.0/classes/ActiveModel/ObserverArray.html#method-i-disable
ORM.observers.disable :user_observer
# => disables the UserObserver
User.observers.disable AuditTrail
# => disables the AuditTrail observer for User notifications.
# Other models will still notify the AuditTrail observer.
ORM.observers.disable :observer_1, :observer_2
# => disables Observer1 and Observer2 for all models.
ORM.observers.disable :all
# => disables all observers for all models.
User.observers.disable :all do
# all user observers are disabled for
# just the duration of the block
end
Where ORM
could for example be ActiveRecord::Base
You could add an accessor to your user model, something like "skip_activation" that wouldn't need to be saved, but would persist through the session, and then check the flag in the observer. Something like
class User
attr_accessor :skip_activation
#whatever
end
Then, in the observer:
def after_save(user)
return if user.skip_activation
#rest of stuff to send email
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With