[ACCEPTED]-Rails 4: How to cancel save on a "before_save" callback?-ruby-on-rails

Accepted answer
Score: 82

Rails 5

As of Rails 5, you can signal that an operation should 19 be aborted by explicitly calling throw :abort inside 18 your callback. The documentation section 17 on cancelling callbacks (now) states:

If a before_* callback throws :abort, all the 16 later callbacks and the associated action 15 are cancelled.

The following section on transactions continues:

If 14 a before_* callback cancels the action a ROLLBACK is issued. You 13 can also trigger a ROLLBACK raising an exception 12 in any of the callbacks, including after_* hooks.

Rails 4

The 11 story is pretty similar to with Rails 5, except 10 that callbacks should instead return false. The 9 corresponding parts of the documentation helpfully states

If 8 a before_* callback returns false, all the later 7 callbacks and the associated action are 6 cancelled. If an after_* callback returns 5 false, all the later callbacks are cancelled.

Followed 4 by

If a before_* callback cancels the action 3 a ROLLBACK is issued. You can also trigger a ROLLBACK 2 raising an exception in any of the callbacks, including 1 after_* hooks.

Score: 33

To prevent record from being saved, you 1 should simply return false:

def check_for_similar_record
  if ProductsColor.exists?(color_id: self.color_id, product_id: self.product_id)
    # merge values
    false
  else
    true
  end
end

More Related questions