Search code examples
ruby-on-railsrubyobserver-pattern

Rails - Can I use observer to cancel the save of a model


I have a before_save observer in one of my models, can I cancel the saving process if a certain condition is matched in the observer?


Solution

  • Yes you can. Just return false from your observer. It will cancel the save.

    At least if you use Rails 3.1 that is. If you use an older version of Rails, you have to define a callback method using:

    class MyModel < ActiveRecord::Base
      before_save :my_callback
    
      def my_callback
        # do something
        false
      end
    end